Simple question regarding Android ImageButtons

Started by
0 comments, last by HellRaiZer 10 years, 10 months ago

Hi all,

I have an Activity that will have many different ImageButtons. I want the user to be able to select one as his choice (it's a sticker app), and continue to the next activity with this choice.

My question is, is there a way to implement only one onClick() method for all the buttons, and distinguish which button the user chose by an ID? for example, if the user selects button2, can I somehow pass the id of button2 to the onClick method in the activity?

The reason for doing this is to prevent repetitive code; the other way to do it is to implement an onClick() method for each sticker, which I think would turn out ugly.

Thanks!

Advertisement

Try creating one View.OnClickListener object and use the View.getID() on the passed view object.

Something like this:


View.OnClickListener listener = new View.OnClickListener()
{
  public void onClick(View v)
  {
    int id = v.getID();
    switch(id)
    {
    case 1000:
      // button0 was clicked...
      break;
    case 1001:
      // button1 was clicked...
      break;
    }
  }
}

button0.setOnClickListener(listener);
button1.setOnClickListener(listener);
...

button0.setID(1000);
button1.setID(1001);
...

Hope that helps.

HellRaiZer

This topic is closed to new replies.

Advertisement