2013-03-27 60 views
0

我寫了一個簡單的應用程序,我想添加一些按鈕programmaticaly。問題是,它不知道要添加多少個按鈕。我試圖把「Button button = new Button」放到for循環中,因爲我只是創建了一個局部變量。我想這是我的錯;)添加未知數量的按鈕programmaticaly

這是我的代碼:

public class MainActivity extends Activity { 

LinearLayout auswahl; 

String element [] = new String [10]; //This is just an example, it would take many pages to show how this array gets created. 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    auswahl = (LinearLayout)findViewById(R.id.LinearLayout2); 

    element [1] = "A"; 
    element [2] = "B"; 
    element [3] = "C"; 
    element [4] = "D"; 
    element [5] = "E"; 
    element [6] = "F"; 
    element [7] = "G"; 
    element [8] = "H"; 
    element [9] = "I"; 
    element [0] = "J"; 

    int anzahl = element.length; 

    for (int i = 0; i <= anzahl; i++){ 
     schreibeButtons(i, element[i]); 
    } 

} 


public void schreibeButtons(int i, String string){ 

    Button button = new Button(this); 

    button.setText(sortiment); 
    button.setWidth(auswahl.getWidth()); 
    button.setHeight(40); 
    button.setId(i*100); 

    auswahl.addView(button); 
} } 

是否有什麼我想達到什麼問題嗎?有誰知道如何達到我的目標?謝謝你的幫助!

+0

第一改變到'I 2013-03-27 18:19:13

+0

男人我是這樣一個白癡 - .-非常感謝你!多數民衆贊成在;) – LosTheAlef 2013-03-27 18:20:32

+0

@ρяσѕρєяK我在輸入相同的答覆兄弟..所以可以停止發佈它。 – Pragnani 2013-03-27 18:20:36

回答

1

錯誤:

int anzahl = element.length; 

大小爲n的陣列包含來自0 to n-1,

prasperK元件已經指出。

您正在將每個按鈕添加到您的LinearLayoutauswahl

你可以從它訪問您的按鈕僅

例:按鈕的數量 - auswahl.getChildCount(); 並且可以訪問這樣

每個按鈕要簡單地通過使用ID

得到按鈕1

Button button1=auswahl.getChildAt(0); 

Button button1=(Button)auswahl.findViewById(101); 
for循環第二條件
+0

非常感謝!這就是我尋找的!只要我有可能做到這一點,我會立即將您的答案設定爲接受;) – LosTheAlef 2013-03-27 18:29:11