tags:

views:

402

answers:

3

I used two image button for Next and Back and i used onclick event for those button i want to which image button fire on onclick and run particular function for next or back in onclick event how will i get which image button fire or onclick event at runtime

+1  A: 

Use View.getId() to distinguish between different views that fire onClick events.

@Override
public void onClick(View view) {
    super.onClick(view);
    switch (view.getId()) {
    case R.id.download:
    //code..
    break;
    case R.id.play:
    //code..
    break;
    case R.id.pause:
        //code..
    break;
    default:
        //code..
    break;
    }
}
Konstantin Burov
hi i am using following concept imgvw_back.setOnClickListener(this)imgvw.setOnClickListener(this);static int i=10;@Overridepublic void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.back: Log.v("back",""+i--); break; case R.id.forward: Log.v("next",""+i++); break; } }but did not work,I don't know,why didnot run?mostly display next word in log
sivaraj
Have you tried to setup a breakpoint at the onClick method? Does it run at all?
Konstantin Burov
+3  A: 

You can use anonymous inner classes to write an onClick function for each button.

Button button1 = getMyButton();
button1.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
      // button 1 was clicked!
   }
  });
Button button2 = getMyButton();
button2.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
      // button 2 was clicked!
   }
  });

As Konstantin mentioned, you can also use the passed in View and switch on the id. However, I find that a bit messier if you end up with lots of clickable things.

Mayra
I'm pretty sure this is the preferred method unless you have a lot of buttons
Falmarri
Thanks for reply
sivaraj
A: 

Hallo Mayra,

Do you know if you could use the same variable, 'button' to set up the listeners? Thereby saving a variable declaration, or do the variables have to remain in scope for the listeners to work?

e.g.

Button button;
button = getMyButton(); // get the first button
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
   // button 1 was clicked!
}
});
button = getMyButton(); // get the second button
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
  // button 2 was clicked!
}
});

-Frink

FrinkTheBrave
You should post these kinds of queries as a separate question (or as a comment), not as an answer. However, yes, that is equivalent (assuming you change the one button2 reference to button). You are effectively assigning the "button" variable to point to two different button objects. You might want to read up on the assignment operator (=).
Mayra
Thanks for Reply
sivaraj