android - 运行时 ScrollView 中的多个 TextView

标签 android android-layout

我试图在运行时将一堆 TextView 添加到 ScrollView ,但我得到 The specified child already has a parent.您必须先对 child 的 parent 调用 removeView

ma​​in.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/

相关文章:

android - android中的谷歌浏览器动画效果

Android SDK的layout_width和layout_height xml属性继承?

java - 获取 java.net.SocketException : recvfrom failed: ECONNRESET (Connection reset by peer)

android - 如何编写 Firebase Android 仪器测试?

android - sendMultipartTextMessage ISms$Stub$Proxy.sendMultipartTextOnSubscription NullPointerException 异常

java - 无法启动 Activity ComponentInfo{com.example.countryselect/com.example.countryselect.OfferSelect}

android - 单击时将 RecyclerView 项目转换为 CardView

java - 使用应用程序 :srcCompat 自定义 ImageView 背景绘制

Android 打印,为什么当我尝试从我的手机打印时收到警告

java - RecyclerView不可见