2011-09-10 67 views
1

我試圖做到這一點按鈕:安卓知道哪個按鈕被按下時創建編程

編程方式創建佈局上4個按鈕。然後,爲每個按鈕創建一個onclick監聽器。然後,根據哪個按鈕被按下,會做一些邏輯。

我在我的XML文件中創建了一個LinearLayout,並將其命名爲「佈局」。

所以,我的代碼去是這樣的:

layout = (LinearLayout)findViewById(R.id.layout); 

    //Create the array of buttons 
    Button [] subjectButtons_BT = new Button[4]; 

    for(int i=0; i<4; i++){ 
     subjectButtons_BT[i] = new Button(this); 
     // Add the button to the layout 
     layout.addView(subjectButtons_BT[i]); 
     subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() { 
       public void onClick(View v) { 
       // if it is the first button, do LOGIC1 
       // if it is the second button, do LOGIC2 etc 
       } 
     }); 
    } 

到目前爲止,我已成功地創建了4個按鈕,我可以按一下按鈕。 但是,我不知道如何在setOnClickListener部分的邏輯。

我想知道哪個按鈕被按下。所以,我嘗試使用v.getId(),但它總是返回-1。

有人可以建議,如果這是正確的路要走嗎?如果是的話,如何做邏輯?

謝謝。

回答

0

您可以設置按鈕的ID在創建之後它們,然後檢查該ID的OnClickListener

layout = (LinearLayout)findViewById(R.id.layout); 

//Create the array of buttons 
Button [] subjectButtons_BT = new Button[4]; 

for(int i=0; i<4; i++){ 
    subjectButtons_BT[i] = new Button(this); 
    subjectButtons_BT[i].setId(i); 
    // Add the button to the layout 
    layout.addView(subjectButtons_BT[i]); 
    subjectButtons_BT[i].setOnClickListener(new Button.OnClickListener() { 
      public void onClick(View v) { 
       int id = v.getId(); 
       if (id == 0) { 
       } else if (id == 1) { 
       } 
       //etc. 
      } 
    }); 
} 
+0

工作得非常好。謝謝。 – alan

2

中有兩個選項用於確定哪些動態按鈕被點擊。

1) Set ID to the button and compare ID 
2) Set Tag to the button if you have come more information about button 
    and want to access it 

1)您可以設置ID的按鈕,並在onClick()方法,你可以通過button.getId()方法得到的ID,你可以比較IDS,並根據點擊執行操作。

2)如果設置了標記,那麼你必須通過調用button.getTag()方法來獲取標記,並通過這種方式,您可以通過對象與按鈕