资源命名参考
Resource naming reference
在我的 android 应用程序中,我有 9 个按钮,参考如下:
R.id.button1;
R.id.button2;
....
R.id.button9
如果我有一个 int 值,假设 int i
包含按钮编号,有没有一种简单的方法可以让我调用引用,例如
String s = "R.id.button" + Integer.toString(i);
Button btn = (Button) findViewbyId(s);
我的代码通过执行 9 if 检查变得越来越冗长。谢谢!
您可以这样尝试从字符串值中获取按钮对象,
String s = "button" + i;
int viewId = getResources().getIdentifier( s, "id", getPackageName());
Button btn = (Button) findViewById(viewId);
在我的 android 应用程序中,我有 9 个按钮,参考如下:
R.id.button1;
R.id.button2;
....
R.id.button9
如果我有一个 int 值,假设 int i
包含按钮编号,有没有一种简单的方法可以让我调用引用,例如
String s = "R.id.button" + Integer.toString(i);
Button btn = (Button) findViewbyId(s);
我的代码通过执行 9 if 检查变得越来越冗长。谢谢!
您可以这样尝试从字符串值中获取按钮对象,
String s = "button" + i;
int viewId = getResources().getIdentifier( s, "id", getPackageName());
Button btn = (Button) findViewById(viewId);