0
我有一個片段,其中我正在對包含線性佈局的frgments視圖以外的項目進行充氣。它膨脹的很好,但現在問題是,當我引用它,並試圖以線性佈局以編程方式添加TextView時,它會導致錯誤。任何幫助將是可取的。java.lang.IllegalStateException:wile將視圖添加到以編程方式膨脹佈局
錯誤: java.lang.IllegalStateException:指定的子項已經有父項。您必須先調用子對象的父對象的removeView()。
Fragment.java
public class ShortFrag extends Fragment{
ListView listview;
LinearLayout row1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.r_fragment, container, false);
listview=(ListView)view.findViewById(R.id.listview);
LayoutInflater myinflater = getLayoutInflater();
ViewGroup myHeader = (ViewGroup) myinflater.inflate(R.layout.helper, listview, false);
row1= headerViewHolder.findViewById(R.id.linear);
TextView tv = getTextView(getTextView("button_one","button"));
//error here
row1.addView(tv);
return view;
}
private TextView getTextView(String text, String tag) {
TextView textView = new TextView(getActivity());
textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.black));
textView.setTag(tag);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewPager.LayoutParams.WRAP_CONTENT
);
textView.setLayoutParams(params);
textView.setGravity(Gravity.CENTER);
textView.setText(text);
textView.setPadding(10, 5, 10, 5);
params.setMargins(10, 0, 10, 0);
return textView;
}
}
r_fragment
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:orientation="vertical">
<Listview
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
helper.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"/>
</LinearLayout>
'row1.add View(getTextView(getTextView(「button_one」,「button」)));' - 使用給定的代碼,將不會編譯,因此永遠不會拋出該異常。什麼是實際的代碼? –
替換此行 row1.addView(getTextView(getTextView(「button_one」,「button」)));與 row1.addView(getTextView(「button_one」,「button」)); – Meenal
邁克你是對的,它解決了我的問題。我編輯了我的問題。但是,你能告訴我這個的原因嗎? –