Reputation: 19
I'm just starting out in java & android.
Below is my code, to add all the buttons in an activity then hide them. Question: is their anyway to automatically add all the buttons in the activity without having to list each of them, I have looked at listA.addall but didn't understand how to add the activity as the collection.
The rational for this is I may wish to change the number of buttons and still have the code work.
public void setup2(){
List<Button> listA = new ArrayList<Button>();
listA.add((Button)findViewById(R.id.button1));
listA.add((Button)findViewById(R.id.button2));
listA.add((Button)findViewById(R.id.button3));
listA.add((Button)findViewById(R.id.button4));
listA.add((Button)findViewById(R.id.button5));
for (Button item : listA)
item.setVisibility(View.INVISIBLE);
}
Upvotes: 0
Views: 579
Reputation: 14472
Assuming that your buttons are in a view group e,g, LinearLayout
:
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v.getClass() == Button.class) {
listA.add(v);
}
}
layout
is a reference to the layout containing the buttons.
This simply iterates over each child view in the layout, compares it's class type with Button
and adds it to your collection if it is.
Upvotes: 0
Reputation: 8543
Yes, that is probably the cleanest way of doing it. But if your buttons are all similarly id named (button_1, button_2 etc) You could search via string instead of direct ID reference. The following is an example of fetching a button by string:
int resID = getResources().getIdentifier("button_%i", "id", getPackageName());
Button addButton = (Button) findViewById(resID);
Then you could loop around all your buttons.
Upvotes: 1