JAAAY JAAAY - 2 months ago 14
Java Question

Android: add dynamically onClickListener on massive widgets

Lets say I have these buttons : b1, b2, b3, b4, b5. I am 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 arrays 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(){
..
}