2012-11-07 18 views
0

我想以編程方式添加一個圍繞TextView和Button的LinearLayout。我希望它接受一個字符串數組,然後使用字符串數組的長度,使用他們自己的按鈕添加許多TextView。Android:以編程方式添加多個Views

所以第一:

String [] s = { .... the values ....} 
int sL = s.length; 
TextView t1 = new TextView (this); 
// then somehow create t2, t3... etc. matching the length of the String array. 

這是做到這一點的最好辦法還是有另一種方式來做到這一點?對於某些情況下,它是一個測驗應用程序,我創建了一個類別列表中的資源內容作爲值,我試圖以編程方式讓我的應用程序創建儘可能多的TextViews,因爲有類別然後設置每個TextView到每個類別然後獲得每個按鈕將用戶帶到該類別的問題。

回答

2

你剛開始的時候,只要做一個for循環,並將textviews添加到你的linearlayout。

// You linearlayout in which you want your textview 
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout); 
linearLayout.setBackgroundColor(Color.TRANSPARENT); 

String [] s = { .... the values ....} 
int sL = s.length; 
TextView textView = null; 

// For later use if you'd like 
ArrayList<TextView> tViews = new ArrayList<TextView>(); 

for (int i = 0; i < sL; i++) 
{ 
    textView = new TextView(this); 
    textView.setText(s[i]); 
    linearLayout.addView(textView); 
    tViews.add(textView); 
} 

這樣做沒什麼問題。如果你想稍後使用這些textview(爲它們設置文本),將它們存儲在某種數組中。編輯的代碼

+0

但他沒有提及這些'TextViews',最好首先將它們放入'List'或'Array'中。 – tolgap

+0

他爲什麼需要參考? =/ –

+1

因爲..他可能會在稍後想用'TextViews'做些什麼? – tolgap

0

你可以做到以下幾點:

for(int i=0;i<s.length;i++){ 
    TextView t=new TextView(this); 
    t.setText(s[i]); 
    yourLinearLayout.addView(t); 
} 

但我真的覺得用一個ListView會獲得更好的性能;)

相關問題