我正在尝试动态处理2D按钮阵列的OnClick侦听器的创建。我通过搜索按钮ID名称的资源来做到这一点,但是尽管正确地在XML中启动了按钮,但我一直遇到以下错误:
java.lang.NoSuchFieldException: No field button00 in class Landroid/widget/Button; (declaration of 'android.widget.Button' appears in /system/framework/framework.jar!classes2.dex
按下按钮如下:button00,button01,button02,button10 ...
事先初始化了一个2D按钮对象:
private boolean zeroTurn = false;
private Button[][] boardButtons = new Button[3][3];
以下内容在我的创建中以解决听众:
for(int x = 0; x< this.boardButtons.length; x++){
for(int y = 0; y< this.boardButtons[x].length; y++){
try {
String buttonname = new StringBuffer("button"+x+y).toString();
boardButtons[x][y] = findViewById(getResId(buttonname,Button.class));
boardButtons[x][y].setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Button clickedB = (Button) view;
Log.d("clickconfirm", "clicked!");
clickedB.setText(zeroTurn ? R.string.t_o:R.string.t_x);
clickedB.setEnabled(false);
zeroTurn = !zeroTurn;
}
});
} catch(Exception e){
e.printStackTrace();
Log.d("Fail", "automation failed");
}
}
}
GetResid函数将字符串和类作为输入,并返回我要搜索的ID:
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
问题在此代码中:
boardButtons[x][y] = findViewById(getResId(buttonname,Button.class));
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
用:
替换这些boardButtons[x][y] = findViewById(getResId(this, buttonname));
public static int getResId(Context context, String buttonname) {
context.getResources().getIdentifier(buttonname, "id", context.getPackageName());
}
这假定您的代码在Activity
内部执行(这似乎是自您打电话给findViewById()
以来的可能性(。如果没有,您需要将真实的Context
实例传递给getResId()
,而不仅仅是this
。
请注意,如果找不到资源ID,这将返回0
而不是-1
。如果您需要 -1
(您不应该这样(,那么您可以这样更改它:
public static int getResId(Context context, String buttonname) {
int id = context.getResources().getIdentifier(buttonname, "id", context.getPackageName());
return (id == 0) ? -1 : id;
}