java.lang.IllegalStateException:以编程方式将视图添加到膨胀布局

时间:2017-04-21 09:24:01

标签: android android-studio android-fragments layout-inflater android-inflate

我有一个片段,我在其中为除了frgments视图之外的项目充气,其中包含线性布局。它正在膨胀很好,但现在的问题是,当我提到它,并尝试以线性布局编程方式添加TextView时,它会导致错误。任何帮助都会更好。

错误: 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>

1 个答案:

答案 0 :(得分:1)

试试这个:

 //error here
 row1.removeAllViews();
 row1.addView(tv);