-3

I'm using MyActivity extends Activity implements OnClickListener{

This activity references around 10+ buttons and has setOnClicklistener(this) method called on every button.

@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...
}
stackoverflow
  • 2,320
  • 3
  • 17
  • 21
LokiDroid
  • 972
  • 10
  • 22

5 Answers5

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

you can use following method to get id.

v.getId()
Avtar Guleria
  • 2,126
  • 3
  • 21
  • 33
1
  @Override 
    public void onClick(View v){
        int id = v.getId();
        if(id == R.id.button_ok){

         }

    }
Mohammad Ersan
  • 12,304
  • 8
  • 54
  • 77
1

The View parameter that is sent to your onClick method is the actual button that was clicked, therefore you can check which one it is, for example:

@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
    }
}

This is only one option, there are other. Search google for more info.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
1

use :

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

or you can even use : Button btn = (Button)findViewById(R.id.btn);

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

but the second one is not recommended.

Yash Patil
  • 469
  • 4
  • 9