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?
TextViewfive times. Move everything except thefindViewById()line to inside your loop. And you probably don't wantMATCH_PARENTparams for both dimensions.TextViews, you need to create five of them.