0

If I have, for example, 30 buttons, and I want to add an OnClickListener to each of them, do I have to manually do button.setOnClickListener(this); for each one? This seems very messy.

Is it possible to use a loop or something?

4 Answers4

7

look this code:

        Button[] b = new Button[30];

        for(int i=0; i < b.length; i++)
        {
            b[i].setOnClickListener(this);
        }

Edit: Before this you need to identify each button using the following loop

       for(int i=0; i< b.length; i++){
            b[i] = (Button) findViewById(R.id.button+i);
       } 
Simon
  • 14,407
  • 8
  • 46
  • 61
javad
  • 833
  • 14
  • 37
1

In case you have different action that needs top be set to each different button, you may use the Array of the onClickListener(s), and then to run on each one of them in the loop. Following example assumes that the number of buttons is equal to the number of listeners.

 Button[] b = new Button[30];
 onClickListener[] myListeners = new onClickListener[30];

 {

//Initialize and add some code to each one of Listeners in the onClick method

 }


for(onClickListener a: myListiners)
{

    b[a.indexof].setOnClickListener(a);

}
Marc Ostan
  • 79
  • 4
0

You can implement the onClickListener interface in your activity and then listen to clicks based on IDs.

    public class MyClickClass implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch(v){
            case R.id.button1:
            //some code
            break;

            case R.id.button2:
           //some code
           break;
          }
       }
    }
Gaurav Bhor
  • 1,057
  • 2
  • 11
  • 26
0

Here, layout is a reference to the parent view group containing your buttons. I am also assuming that your Activity extends onClickListener (.setOnClickListener(this)). If not, then just pass a reference to your onclick() method.

for (int i = 0; i < layout.getChildCount(); i++) {
    View v = layout.getChildAt(i);
    Class c = v.getClass();
    if (c == Button.class) {
       ((Button)v).setOnClickListener(this);
    }
}

With a little effort, this could be made to be recursive if all of your buttons do not exist in the same view group. You could then recurse down from the root view group.

Simon
  • 14,407
  • 8
  • 46
  • 61