问题
Say for example I define several buttons in my XML file and initially set them as disabled.
<Button
android:text="Off"
android:id="@+id/Button0"
android:enabled="false">
</Button>
<Button android:text="Off"
android:id="@+id/Button1"
android:enabled="false">
</Button>
<Button android:text="Off"
android:id="@+id/Button2"
android:enabled="false">
</Button>
<Button android:text="Off"
android:id="@+id/Button3"
android:enabled="false">
</Button>
Later on in my code I then want to enable ALL the buttons so ideally this should be done in a loop but I cannot work out how I can get access to the buttons ins a loop. e.g. I do not want to put several statements:
Button b = (Button)findViewById(R.id.Button0);
/* Do some action on button0 */
b = (Button)findViewById(R.id.Button1);
/* Do some action on button1 */
/* And continue with explicit statements for each button*/
So how can I achieve the above in a loop?
回答1:
My advice: Create a static final array of integers containing the IDs of the buttons, e.g.:
private static final int[] BUTTONS = {
R.id.Button0,
R.id.Button1,
...
};
Then you can iterate over that.
来源:https://stackoverflow.com/questions/5448658/how-can-i-loop-over-several-button-views