2011-04-23 38 views
5

我寫了下面的代碼,但沒有得到如何爲所有按鈕編寫OnclickListner()方法。如何在運行時創建多個按鈕? + android

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    LinearLayout layout = (LinearLayout) findViewById(R.id.ll1Relative); 
    for (int i = 1; i < 10; i++) { 
     LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT 
     ); 
     Button b = new Button(this); 
     b.setText(""+ i); 
     b.setId(100+i); 
     b.setWidth(30); 
     b.setHeight(20); 
     layout.addView(b, p); 
    } 
} 

回答

2

您可以使用這樣一個匿名的內部方法:如果你想的按鈕做不同的事情

Button b = new Button(this); 
b.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
     // Perform action on click 
    } 
}); 
b.setText("" + i); 
b.setTag("button" + i); 
b.setWidth(30); 
b.setHeight(20); 
+0

事情是我想寫的SQLite分別查詢每個按鈕。是否最好使用swith case?有10個按鈕,每個都有單獨的查詢。 – Pramod 2011-04-23 09:35:54

0

,你可以有你的活動延長OnClickListener,在迴路設置b.setOnClickListener(this),並添加像

@Override 
public onClick(View v) 
{ 
    // get who called by 
    String sTag = (String) v.getTag(); 

    if (sTag.equals("button1")) 
    { 
    //do some stuff 
    } 
    else if (sTag.equals("button2")) 
    { 
    //do some other stuff 
    } 
    // and so on 
} 

來處理點擊。


而且我在這裏編輯,是因爲缺少換行符使得意見明確:

int iBtnID = v.getId(); 
switch (iBtnID) 
{ 
    case 101: 
    // do stuff; 
    break; 
    case 102: 
    // do other stuff 
    break; 
    // and so on 
} 
+0

insted的標籤我使用setId(),請你解釋一下switch case的含義。 – Pramod 2011-04-23 09:47:41

+0

@Pramod:編輯開關/案例到我以前的答案。 :) – 2011-04-23 10:04:24

-1
LinearLayout lin = (LinearLayout) findViewById(R.id.linearLayout); 

Button b1 = new Button(this); 


b1.setText("Btn"); 
b1.setId(int i=2); 
b1.setonClicklistenor(this); 
lin .addView(b1); 

onclick (View v){ 


int i=v.getId(); 

if (i==2){ 

///operation 
} 
} 
} 
+1

我不明白這是如何回答這個問題。 OP的問題是如何處理按鈕的點擊事件。 – Michael 2014-07-21 10:29:09