Java 在Android上动态添加TextView到ScrollView

Java 在Android上动态添加TextView到ScrollView,java,android,android-activity,Java,Android,Android Activity,我试图使ScrollView像ListView一样工作。因此,每一行都是动态添加的TextView。但是程序崩溃了。我在线性布局中有一个滚动视图。我做错了什么?谢谢 这是我的密码 scroll = (ScrollView)findViewById(R.id.scrollView1); layout = (LinearLayout) findViewById(R.id.LinearLayout1);

我试图使ScrollView像ListView一样工作。因此,每一行都是动态添加的TextView。但是程序崩溃了。我在线性布局中有一个滚动视图。我做错了什么?谢谢

这是我的密码

                        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);
scroll=(ScrollView)findViewById(R.id.scrollView1);
布局=(线性布局)findViewById(R.id.LinearLayout1);
布局。setBackgroundColor(颜色。透明);
TextView[]tx=新的TextView[10];
对于(int i=0;i<10;i++){
tx[i]=新文本视图(HelloWorldActivity.this);
tx[i].setLayoutParams(新的LayoutParams(LayoutParams.MATCH_父级,LayoutParams.MATCH_父级));
tx[i].setText(“这是textviewNo”+i);
布局。添加视图(tx[i]);
}
滚动。添加视图(布局);
XML:



滚动视图只能有一个子视图。如果尝试向滚动视图添加多个子视图,则它将崩溃。您应该将LinearLayout放在scrollview的内部,然后将TextView动态添加到线性布局中

您试图将
线性布局1
添加为自己孩子的孩子(成为自己的祖父是一个令人困惑的概念)

将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>

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


现在还不清楚您想要实现什么,但是使用listview来实现这一点有什么错呢?您可以在listview上设置最大高度。或者您可以尝试wdziemia的建议

请添加您的logcat错误。“程序崩溃”太模糊了。眼光不错,但作者添加了一个线性布局作为ScrollView的子级,
scroll.addView(布局)
在这种情况下,子视图也是ScrollView的父视图,这是错误的。(那首《解脱》中的歌曲是什么?+1是的,LinearLayout1已经添加到xml中,您再次将其添加到java中(重新为其设置父子关系)。。。。。。
<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>