Mani Sankar Mani Sankar - 5 months ago 38
Android Question

Error while adding multiple Views to a LinearLayout programatically

I was trying to add a

View
multiple times by using a for loop, but I was getting an error

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


My XML file

<?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>


My class file

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);
}


Where am I going wrong?

Answer

You cannot add the same View multiple times to the same layout.

The following should work:

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);
}

Also, setting either the height or the width (maybe both, depending on the orientation of your LinearLayout) of the TextView to WRAP_CONTENT might make more sense.

Comments