2011-10-31 100 views
1

如果我在android中有一个按钮数组,并希望通过for循环获取这些按钮(findviewbyid),我该怎么做?可以说我有我的XML定义button1,button2和button3。如何将arr [0],arr [1]和arr [2]分配给这些?For object with object

for(int a = 0; a < arr.length; a++){ 
    arr[a] = (Button) findViewById(R.id.button[a + 1]); //Doesn't work 
} 

在此先感谢!

回答

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); 
} 
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); 
} 
+0

几乎多余的答案。 –

相关问题