2012-06-11 87 views
0

我試着讓ScrollView像ListView一樣工作。所以每一行都將是一個動態添加的TextView。但程序崩潰。我在LinearLayout中有一個ScrollView。我做錯了什麼?謝謝。在Android上動態添加TextView到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

請添加您的logcat錯誤。 「程序崩潰」太模糊了。 – Sam

回答

1

滾動型只能有一個孩子。如果您嘗試向滾動視圖添加多個子項,則會崩潰。您應該在滾動視圖中使用LinearLayout,然後將textViews動態添加到線性佈局。

+0

好眼,但作者正在添加一個LinearLayout作爲ScrollView的子元素,'scroll.addView(layout);'在這種情況下,子元素也是ScrollView的父元素,這是錯誤的。 (Deliverance的那首歌是什麼?) – Sam

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> 
+0

+1是的LinearLayout1已經添加到xml中,並且你再次用java添加它(重新加載它)...... –

0

不能看法添加到滾動視圖。您只能將它們添加到視圖組,如線性或相關佈局。

這並不完全清楚你想要實現什麼,但是使用listview來做這件事有什麼問題?你可以在列表視圖上設置最大高度。或者你可以嘗試wdziemia的建議