动态添加 TextView 到 Android 上的 ScrollView



我尝试使ScrollView像ListView一样运行。因此,每一行都将是动态添加的文本视图。 但是程序崩溃了。我在LinearLayout中有一个ScrollView。我做错了什么?谢谢。

这是我的代码

                        scroll = (ScrollView)findViewById(R.id.scrollView1);
                    layout = (LinearLayout) findViewById(R.id.LinearLayout1);
                    layout.setBackgroundColor(Color.TRANSPARENT);
                    TextView[] tx = new TextView[10];
                    for (int i = 0; i < 10; i++) {
                        tx[i] = new TextView(HelloWorldActivity.this);
                        tx[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                    tx[i].setText("This is the textviewNo" + i);
                    layout.addView(tx[i]);
                    }
                    scroll.addView(layout);

.XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
    android:id="@+id/timeflag"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="50sp" 
    android:gravity="center"/>

<Button
    android:id="@+id/pause"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/timeflag"
    android:layout_marginTop="37dp"
    android:text="Start" />

<LinearLayout
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/pause"
    android:orientation="vertical" >
    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ScrollView>
</LinearLayout>
</RelativeLayout>

滚动视图 只能有一个孩子。如果您尝试将超过 1 个孩子添加到滚动视图中,那么它将崩溃。您应该在滚动视图中具有线性布局,然后将文本视图动态添加到线性布局中。

您正在尝试将LinearLayout1添加为自己孩子的孩子(成为您自己的祖父,这是一个令人困惑的概念)。

像这样更改您的 XML:

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/pause"
    >
    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>
</ScrollView>

不能向滚动视图添加视图。您只能将它们添加到视图组,如线性或相对布局。

目前还不清楚您要实现的目标,但是为此使用列表视图有什么问题?您可以在列表视图上设置最大高度。或者你可以试试wdziemia的建议

最新更新