在我的xml布局文件中,我有81个按钮:
<Button
android:id="@+id/button11"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
我知道我可以这样得到参考:
playButtons[0][0] = (Button) findViewById(R.id.button11);
playButtons[0][1] = (Button) findViewById(R.id.button12);
等等,但我怎样才能有效地做到这一点?
编辑:
我想用for循环中的XML按钮填充我的playButtons矩阵,如下所示:
for(int i = 0; i<9; i++){
for(int k = 0; k<9; k++){
playButtons[i][k] = (Button) findViewById(R.id.button11);}}
但我不知道如何将button11更改为button12,依此类推。
答案 0 :(得分:2)
我认为这就是你想要的。您必须将按钮命名为button01,button02,button03等。
Button[][] playButtons = null;
Class id=R.id.class;
Field field = null;
for(int i = 0; i<9; i++){
for(int k = 0; k<9; k++){
try {
field = id.getField("button"+i+""+k);
playButtons[i][k] = (Button) findViewById(field.getInt(null));
} catch (NoSuchFieldException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
答案 1 :(得分:1)
您是否考虑过listview或gridview?如果你可以使用效率更高的那些中的任何一个。如果不是,您将不得不逐个声明每个按钮,但如果您使用playButtons数组,则可以使用循环将更改应用于所有按钮,例如
for(int i = 0;i<playButtons.length;i++){
playButtons[0][i].setOnClickListener(this);
}
这将是我能想到的最有效的方式......
答案 2 :(得分:0)
我建议您将此语法用于您的ID,这样您就不会对应用中大量的ID感到困惑:
android:id="@+id/your_file_name_widgetName_whatYourWidgetDo
在名为 menu_settings.xml
的布局文件中保存设置预设的按钮示例android:id="@+id/menu_settings_button_savePreset"
当我的XML文件上有很多按钮时,我会在数组上注册它,如下所示:
final int[] BUTTON_ID = {
R.id.myId, R.id.anotherId, R.id.otherId,
R.id.moreId, R.id.anotherAnotherId
};
final int BUTTONS_COUNT = BUTTON_ID.lenght;
Button[] button;
@Override
public void onCreate(Bundle savedInstanceState){
...
button = new Button[BUTTONS_COUNT];
for(int i = 0; i < BUTTONS_COUNT; i++){
button[i] = (Button) findViewById(BUTTONS_ID[i]);
button[i].setOnClickListener(this); // your class should implements View.onClickListener to use "this" as argument
}
}
你告诉你布局上有81个按钮,findViewById()
里面的for
循环会导致低性能循环,我建议你将android:onClick = "methodName"
attr添加到xml上的按钮上文件,因此您不需要为每个使用findViewById()
。
要使用按钮,只需将以下内容添加到Activity类中,然后执行任何操作:
public void methodName(View v){
Button b = (Button) v;
int ID = b.getId();
if(ID == R.id.buttonId){
//DO SOMETHING FOR THIS BUTTON
}
else if(ID == R.id.anotherButtonId){
//DO SOMETHING FOR THIS BUTTON
}
...
}
但请想一想:你的布局上需要这么多按钮吗?想想一个更好的应用程序架构,81个按钮对于单个线程来说可能非常重。
我希望你明白这个想法!