Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all Buttons ID's in one time on Android

I have 16 Buttons in my Activity and I have to initialize those inside onCreate(). Is there any way to initialize all buttons in one single line code?(loops etc.) Code should take all buttons R.id. from XML Layout and process....

like image 920
Ertuğrul Çetin Avatar asked Mar 25 '14 15:03

Ertuğrul Çetin


2 Answers

Let's say you named your button button_0, button_1, .. button_15. You can do:

for (int i = 0; i < 16; i++) {
    int id = getResources().getIdentifier("button_"+i, "id", getPackageName());
    button[i] = (Button) findViewById(id);
}
like image 87
Blackbelt Avatar answered Nov 24 '22 03:11

Blackbelt


Well, if all 16 of those buttons are inside one view or layout, then you could do the following.

ArrayList<View> allButtons; 
allButtons = ((LinearLayout) findViewById(R.id.button_container)).getTouchables();

This assumes that your container (in this example a LinearLayout) contains no Touchable that is not a Button.

like image 25
Rudi Kershaw Avatar answered Nov 24 '22 03:11

Rudi Kershaw