我有以下按钮视图
button1 = (Button) findViewById(R.id.button0);
button2 = (Button) findViewById(R.id.button1);
button3 = (Button) findViewById(R.id.button2);
button4 = (Button) findViewById(R.id.button3);
button5 = (Button) findViewById(R.id.button4);
button6 = (Button) findViewById(R.id.button5);
button7 = (Button) findViewById(R.id.button6);
button8 = (Button) findViewById(R.id.button7);
这个Button []:
Button[] buttonViewsArray = new Button[8];
我想使用for循环将按钮添加到数组中,但不确定如何使用i
变量然后引用正确的按钮:
int i;
for (i = 0; i < buttonViewsArray.length; i++){
String j = "button" + i;
Button[i] = findViewById(j);
}
我想可能会创建一个引用正确viewID的String
?
答案 0 :(得分:1)
是的,可以在循环中获取资源。以下是我放在一起的Sudoku应用程序中的示例(TextViews具有表格的名称&#34; tv32&#34;):
// get the text views using dynamic layout IDs
for( int row=0; row<9; row++ )
for( int col=0; col<9; col++ )
{
int layoutID = getResources().getIdentifier("tv"+row+col, "id", getPackageName());
tv[row][col] = (TextView) findViewById(layoutID);
// set text for testing
//tv[row][col].setText(""+row+col);
// set up to respond to click
tv[row][col].setOnClickListener( new CellOnClickListener(row, col) );
}
答案 1 :(得分:0)
不,R.id.button6
是R文件中的整数。
如果需要,您必须为每个按钮调用findViewById并将它们保存在数组中。