У меня есть код в программировании для 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
SO есть два способа сделать это 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
Танки Все.