Android:通过 for 循环将按钮连接到 java 文件

Android: Connecting buttons to the java file through a for loop

我正在尝试为 Android 创建一个国际象棋游戏,并且希望避免在每个按钮的名称都如此相似时声明每个按钮。我尝试使用此 for 循环生成所有 A + Num 按钮。

int RowNum ;
for (RowNum = 1; RowNum < 8; RowNum++) {
    String Position = "A" + RowNum;
    Button Position = (Button)findViewById(R.id.Position);
}

但是我有一个错误:变量 'Position' 已经在范围内定义。

如果有人能向我解释执行此操作的最佳方法,我将不胜感激。

提前致谢。

您将 String Button 对象都称为 Position。给他们不同的名字,例如

for (int RowNum = 1; RowNum < 8; RowNum++) {
    String currentPosition = "A" + RowNum;
    //Why doesn this not use the Position (now 'currentPosition' variable)?
    Button currentButton = (Button)findViewById(R.id.Position);
} 

语义上我仍然没有得到那段代码,因为 Position 没有在 findViewById 的参数中使用,你向它传递了一个静态变量 R.id.Position.

R.Id.A1、R.id.A2 等是 identifiers,在 R class 的编译期间,它们中的每一个都被映射到一个整数。因此,您不能将 'R.id.sth' 作为字符串进行操作,因为它无法正确编译。

解决这个问题的一种方法是使用如下代码在资源中动态搜索字符串:

Button[] buttons=new Button[8]; 
for(int RowNum=0; RowNum<8; RowNum++) {
   String buttonID = "A"+(RowNum+1); 
   int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
   buttons[RowNum] = ((Button) findViewById(resID));
}

或者,为了避免动态搜索的时间开销,您可以添加一个资源数组:

int[] butIds = {R.id.A1, R.id.A2,...};

Button[] buttons= new Button[8]; 
    for(int RowNum=0; RowNum<8, RowNum++) {
       buttons[RowNum]= ((Button) findViewById(butIds[RowNum]));
}

您甚至可以将资源数组存储为 XML 形式并将其检索为 TypedArray