如果我在 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<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);
}
关于android - 带有对象名称的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7953809/