Android 对于具有对象名称的循环
如果我在android中有一组按钮,并且希望通过for循环获得这些按钮(findviewbyid),我该怎么做?假设我在xml中定义了button1、button2和button3。如何将arr[0]、arr[1]和arr[2]分配给这些对象Android 对于具有对象名称的循环,android,android-layout,Android,Android Layout,如果我在android中有一组按钮,并且希望通过for循环获得这些按钮(findviewbyid),我该怎么做?假设我在xml中定义了button1、button2和button3。如何将arr[0]、arr[1]和arr[2]分配给这些对象 for(int a = 0; a < arr.length; a++){ arr[a] = (Button) findViewById(R.id.button[a + 1]); //Doesn't work } for(int a=0;a
for(int a = 0; a < arr.length; a++){
arr[a] = (Button) findViewById(R.id.button[a + 1]); //Doesn't work
}
for(int a=0;a
提前谢谢 尝试实现这一点:
for(int a=0; a<arr.length; a++) {
String buttonID = "btn" + a;
int resID = getResources().getIdentifier(buttonID, "id", "com.package.your_app");
// To fetch Package name, you can directly call getPackageName() instead of static string "com.package.your_app
buttons[a] = ((Button) findViewById(resID));
buttons[a].setOnClickListener(this);
}
for(int a=0;a试着实现这一点:
for(int a=0; a<arr.length; a++) {
String buttonID = "btn" + a;
int resID = getResources().getIdentifier(buttonID, "id", "com.package.your_app");
// To fetch Package name, you can directly call getPackageName() instead of static string "com.package.your_app
buttons[a] = ((Button) findViewById(resID));
buttons[a].setOnClickListener(this);
}
对于(int a=0;a则此工作:
for(int a = 0; a < arr.length; a++) {
String buttonId = "btn" + String.valueOf(a);
int resButton = getResources().getIdentifier(buttonId, "id", "com.package.your_app");
arr[a] = (Button) findViewById(resButton);
}
for(inta=0;a
那么这项工作:
for(int a = 0; a < arr.length; a++) {
String buttonId = "btn" + String.valueOf(a);
int resButton = getResources().getIdentifier(buttonId, "id", "com.package.your_app");
arr[a] = (Button) findViewById(resButton);
}
for(inta=0;a