2011-09-04 16 views

回答

0

每個Button對象都是一個視圖本身。因此,它可以添加到父佈局(如LinearLayout)。恕我直言,最簡單的方法是創建XML僅用於您知道不會更改的內容,或者可能使用TableLayout。然後,添加按鈕。

LinearLayout mainLayout = findViewById(R.id.mainLayout); 
Button[] btnArray = new Button[3]; 
for(Button button : btnArray){ 
    button = new Button(/*Required params */); 
    // button.something , play with text and onclick and positions... 
    mainLayout.addView(button); 
} 

這是你想要做的嗎?

+0

是的,但可以ü解釋參數Code有點當我試圖做到這一點,這是我的參數Code是我搞砸了在最 –

+0

你應該粘貼代碼,以便我們可以找出哪裏是一團糟。 –

0
LinearLayout linear = (LinearLayout) findViewById(R.id.linear); 
for (int i = 1; i <= 20; i++) { 
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.MATCH_PARENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT); 
    btn = new Button(this); 
    btn.setId(i); 
    final int id_ = btn.getId(); 
    btn.setText("button " + id_); 
    btn.setBackgroundColor(Color.rgb(70, 80, 90)); 
    linear.addView(btn, params); 

    btn1 = ((Button) findViewById(id_)); 
    btn1.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 
      Toast.makeText(view.getContext(), 
        "Button clicked index = " + id_, Toast.LENGTH_SHORT) 
        .show(); 
     } 
    }); 
}