2013-05-01 60 views
-3

視圖的ID我使用10+左右按鍵MyActivity extends Activity implements OnClickListener{檢索該被點擊

此活動引用,並具有setOnClicklistener(this)方法叫上每個按鈕。

@Override 
public void onClick(View v){ 
    //here I need to get the id of the view that was clicked... 
    //Depending on the button that was clicked different actions need to be called... 
    //How do I get the ID of the button that was clicked... 
} 
+0

使用開關盒 – stackoverflow 2013-05-01 10:21:47

+2

爲什麼不先谷歌它? http://developer.android.com/reference/android/view/View.html#getId() – httpdispatch 2013-05-01 10:21:58

+0

首先使用google。 – 2013-05-01 10:24:12

回答

3
@Override 
public void onClick(View v){ 
switch(v.getId()){ 
    case R.id.btnCancel: 
     //your code for onclick of that button 
     break; 
} 
1

你可以用下面的方法來獲得ID。

v.getId() 
1
@Override 
    public void onClick(View v){ 
     int id = v.getId(); 
     if(id == R.id.button_ok){ 

     } 

    } 
1

發送到您的onClickView參數是實際的按鈕被點擊,因此,你可以檢查它是哪一個,例如:

@Override 
public void onClick(View v){ 
    switch(v.getId()) { 
     case R.id.button_1: ...; break; 
     case R.id.button_2: ...; break; 
     case R.id.button_3: ...; break; 
     ... 
     default: //unknown button clicked 
    } 
} 

這只是一個選項,還有其他的。搜索谷歌瞭解更多信息。

1

使用:

if(v.getId()==R.id.whatever) 
{ 
// do something 
} 

,或者你甚至可以使用: 按鈕BTN =(按鈕)findViewById(R.id.btn);

if(v==btn) 
{ 
// do something 
} 

但第二個不推薦。