2011-10-28 101 views
1

我試着讓ScrollView像ListView一樣工作。 每一行都將是一個動態添加的TextView。 所以我嘗試這個代碼在Android上動態添加TextView到ScrollView

this.scrollView = (ScrollView) findViewById(R.id.scrollView1); 
this.linearLayout = (LinearLayout) findViewById(R.id.linearLayout2); 
this.linearLayout.setOrientation(LinearLayout.VERTICAL); 
TextView[] tx = new TextView[10]; 
for (int i = 0; i < 10; i++) { 
    tx[i] = new TextView(this); 
    tx[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
tx[i].setText("This is the textviewNo" + i); 
this.linearLayout.addView(tx[i]); 
} 
this.scrollView.addView(this.linearLayout); 
setContentView(this.scrollView); 

,但我得到這個異常

10-28 13:35:59.120: ERROR/AndroidRuntime(2346): Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child 

在行this.scrollView.addView(this.linearLayout) 我該怎麼辦了? 謝謝

回答

4

異常很清楚:你不能添加多個孩子到ScrollView。從你的代碼我假設linearLayout2已經在ScrollView內?如果是這樣,比你不需要

this.scrollView.addView(this.linearLayout); 

可言,因爲你加TextViews到的LinearLayout這已經是滾動型