JAAAY JAAAY - 2 months ago 17
Android Question

Android massively and dynamically add onClickListener

Lets say I have these buttons : b1, b2, b3, b4, b5. I searching how to do this:

ArrayList<Button> bAL = new ArrayList<>();
for (int i=1; i<=5; i++){
bAL.add((Button) findViewById(R.id.b+[i])) //The expression should equal to R.id.b1 or R.id.b2 or..
bAL.get(i).setOnclickListener(new View.onClickListener{...});
}


Anybody has an idea?

Answer

All ID's are integer so the simplest way is to put them in an integer array and use them plus array are easy to manipulate (add/remove ids). In case you don't want to manipulate the ID array then mark it as final ( will add little for efficiency ).

       int ar[]={R.id.button1,R.id.button2,R.id.button3}

        ArrayList<Button> bAL = new ArrayList<>();
        for (int i=1; i<=5; i++){
            bAL.add((Button) findViewById(ar[i])); 
            bAL.get(i).setOnclickListener(listener);  // have a listener and just use the refereance

        }

View.onClickListener  listener =new View.onClickListener(){
..
}