How can I LOOP over several Button Views?

China☆狼群 提交于 2019-12-10 11:11:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!