2010-03-14 63 views
4

如何設置OnClickListener來簡單告訴我哪個索引按鈕是從一組按鈕中按下的。我可以使用數組更改這些按鈕的文本和顏色。我把它們設置成這樣。Android中按下了按鈕索引的按鈕

TButton[1] = (Button)findViewById(R.id.Button01); 
TButton[2] = (Button)findViewById(R.id.Button02); 
TButton[3] = (Button)findViewById(R.id.Button03); 

高達36

回答

9

的OnClickListener將要接收該按鈕本身,如R.id.Button01。這不會讓你回到你的數組索引,因爲它不知道如何引用存儲在數組中的所有按鈕。

您可以直接使用傳遞給onClickListener的按鈕,而不需要數組中的額外查找。如:

void onClick(View v) 
{ 
    Button clickedButton = (Button) v; 

    // do what I need to do when a button is clicked here... 
    switch (clickedButton.getId()) 
    { 
     case R.id.Button01: 
      // do something 
      break; 

     case R.id.Button01: 
      // do something 
      break; 
    } 
} 

如果你真的在尋找被點擊的按鈕的數組索引設置,那麼你可以這樣做:

void onClick(View v) 
{ 
    int index = 0; 
    for (int i = 0; i < buttonArray.length; i++) 
    { 
     if (buttonArray[i].getId() == v.getId()) 
     { 
     index = i; 
     break; 
     } 
    } 

    // index is now the array index of the button that was clicked 
} 

但是,這真的好像最沒有效率的方法去做這件事。也許如果你提供了更多關於你在OnClickListener中試圖完成的信息,我可以給你更多的幫助。

+0

這是一張門票。我只想索引號 - 交換機做一些事情會是案件R.id.Button01:index = 1。謝謝你mbaird! – 2010-03-14 23:46:20

1

您可以設置標籤值,並獲得點擊標籤:

TButton[1] = (Button)findViewById(R.id.Button01); 
TButton[1].setTag(1); 


onClick(View v) 
{ 
    if(((Integer)v.getTag())==1) 
    { 
    //do something 
    } 
}