Android - 使用for循环向数组添加视图

时间:2015-11-23 03:12:18

标签: java android for-loop

我有以下按钮视图

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

2 个答案:

答案 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并将它们保存在数组中。

相关问题