我试图在运行时将一堆 TextView 添加到 ScrollView ,但我得到 The specified child already has a parent.您必须先对 child 的 parent 调用 removeView
。
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>
测试应用
@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);
}
最佳答案
您不能像这样在单个 Activity
中使用两次 setContentView()
。这就是问题所在。
看这个回答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.
关于android - 运行时 ScrollView 中的多个 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11063280/