如果我在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
}
提前致谢!
答案 0 :(得分:4)
尝试实施此目的:
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);
}
答案 1 :(得分:0)
然后这项工作:
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);
}