我在android编程中有以下代码
Button btn1 = ( Button ) findViewById( R.id.btn1 );
Button btn2 = ( Button ) findViewById( R.id.btn2 );
Button btn3 = ( Button ) findViewById( R.id.btn3 );
Button btn4 = ( Button ) findViewById( R.id.btn4 );
Button btn5 = ( Button ) findViewById( R.id.btn5 );
Button btn6 = ( Button ) findViewById( R.id.btn6 );
Button btn7 = ( Button ) findViewById( R.id.btn7 );
Button btn8 = ( Button ) findViewById( R.id.btn8 );
Button btn9 = ( Button ) findViewById( R.id.btn9 );
它一直持续到 btn30
在 python 中我通过下面的简单代码对其进行优化
#is a python syntax (for_statement)
#python work by tab
for i in range(1,31):
#in python not need to declare temp
temp="""Button btn"""+str(i)+"""=(Button)findViewById(R.id.btn"""+str(i)+""")"""
exec(temp)#a default function in python
在 java 编程中我该怎么做?或者我可以做到吗?确实存在一个简单的代码吗?
UPDATE 1
所以有两种方法可以做到
Code 1
:
final int number = 30;
final Button[] buttons = new Button[number];
final Resources resources = getResources();
for (int i = 0; i < number; i++) {
final String name = "btn" + (i + 1);
final int id = resources.getIdentifier(name, "id", getPackageName());
buttons[i] = (Button) findViewById(id);
}
Code 2
:
public static int getIdByName(final String name) {
try {
final Field field = R.id.class.getDeclaredField(name);
field.setAccessible(true);
return field.getInt(null);
} catch (Exception ignore) {
return -1;
}
}
final Button[] buttons = new Button[30];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (Button) findViewById(getIdByName("btn" + (i + 1)));
}
另一种方式是 GidView