如何优化包含一些重复行的代码?

2022-09-04 05:29:19

我在安卓编程中有以下代码

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


答案 1

您可以创建一个数组 ,并使用方法,该方法允许您按其名称获取标识符。ButtongetIdentifier

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);
}

如果有人有兴趣,如何仅使用Java获得相同的结果

上面的解决方案使用特定的方法(例如,),并且不能在通常中使用,但是我们可以使用并编写一个像:AndroidgetResourcesgetIdentifierJavareflectiongetIdentifier

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)));
}

答案 2

与其优化这种代码,不如重新考虑布局。如果屏幕上有30个按钮,则可能是更好的解决方案。您可以通过索引访问项目,并像使用按钮一样处理事件。ListViewonClick


推荐