Reputation: 113
I'm trying to add a bunch of TextViews at runtime to a scrollview but I get The specified child already has a parent. You must call removeView on the child's parent first
.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
testapp
@Override
public void onCreate(Bundle savedInstanceState) {
TextView[] data;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View layout = findViewById(R.id.layout);
.......................................
data = new TextView[10];
for (int i = 0; i < 10; i++) {
data[i] = new TextView(this);
data[i].setText("data = " + i);
((ViewGroup) layout).addView(data[i]);
}
setContentView(layout);
}
Upvotes: 1
Views: 952
Reputation: 54322
You cannot use setContentView()
twice in a single Activity
like this. That's the problem.
Look at this answer here:
A view can only have a single parent. The view that you are adding (I am guessing re-using) is already part of another view hierarchy. If you really want to reuse it (I would suggest you probably don't) then you have to detach it from its parent in its existing view hierarchy.
Upvotes: 1
Reputation: 15701
I think the problem is of layout variable.
it already has a parent ScrollView view as per XML now when you are using this setContentView(layout); so this try to add layout in different parent ..
Upvotes: 1