以编程方式将多个视图添加到LinearLayout时出错

时间:2016-06-24 07:32:29

标签: android

我试图通过使用for循环多次添加View,但是我收到了错误

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

我的XML文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_display_list"
    android:id="@+id/root_layout">
</LinearLayout>

我的班级文件

ViewGroup ll = (ViewGroup) findViewById(R.id.root_layout);
TextView tv = (TextView) new TextView(this);
tv.setText("helloworld");
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));

//adding views in loop
for(int i=0;i<=5;i++)
{
    ll.addView(tv);
}

我哪里错了?

4 个答案:

答案 0 :(得分:3)

您无法多次向同一布局添加相同的View

以下内容应该有效:

ViewGroup ll = (ViewGroup) findViewById(R.id.root_layout);

for(int i=0; i<=5; i++)
{
    TextView tv = (TextView) new TextView(this);
    tv.setText("helloworld");
    tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    ll.addView(tv);
}

此外,设置LinearLayoutTextView的高度或宽度(可能两者,取决于WRAP_CONTENT的方向)可能更有意义。

答案 1 :(得分:0)

你应该使用LinearLayout,并且每次都需要创建textview和params,因为你不能多次添加单个视图 -

    LinearLayout ll = (LinearLayout) findViewById(R.id.root_layout);

          //adding views in loop
          for(int i=0;i<=5;i++)
          {
             TextView tv = (TextView) new TextView(this);
             tv.setText("helloworld");
             ll.addView(tv, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
          }

希望它会有所帮助:)

答案 2 :(得分:0)

试试这个:

for(int i=0;i<=5;i++){
    ViewGroup ll = (ViewGroup) findViewById(R.id.root_layout);
    TextView tv = (TextView) new TextView(this);
    tv.setText("helloworld");
    tv.setLayoutParams(new        LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));

    ll.addView(tv);

}

答案 3 :(得分:-1)

尝试一下,可能有帮助..

 //adding views in loop
    for(int i=0;i<=5;i++)
    {
    if(tv.getParent()!=null)
    {
        ((ViewGroup)tv.getParent()).removeView(tv);
    }
    ll.addView(tv); 
}

感谢..