基于findViewById中的名称的动态访问



抱歉,标题有点模糊,

问题在下面。我想使用x变量来迭代这个对象它在名称(R.id.imageButtonx)

中使用了1 -9个值
for (int x = 1; x <10; x++)
    mm.add((Button) findViewById(R.id.imageButtonx));

//再深入一点。

我从一个Button数组开始然后我这样做:

 main_Menu = new Button[] {
            (Button) findViewById(R.id.imageButton1),
            (Button) findViewById(R.id.imageButton2),
            (Button) findViewById(R.id.imageButton3),
            (Button) findViewById(R.id.imageButton4),
            (Button) findViewById(R.id.imageButton5),
            (Button) findViewById(R.id.imageButton6),
            (Button) findViewById(R.id.imageButton7),
            (Button) findViewById(R.id.imageButton8),
            (Button) findViewById(R.id.imageButton9)
        };

所以我可以做两行foreach循环来附加onbuttonclicklistener

所以我想知道我是否可以把这十行减少到两行。我转向了数组列表。我希望x变量周围是方括号,圆括号,单引号,双引号之类的东西但从一个答案来看,这似乎是不可能的。

Java不使用循环变量替换imageButtonx中的"x"。

但是,您可以创建一个imageButton id数组,并通过索引引用它们。

如果你指的是android

像这样使用Resources.getIdentifier()

int id = getResources().getIdentifier("imageButton" + x, "id", null);
String s = getString(id);

根据您的确切需求,您可以使用一个单独的函数执行类似的操作,该函数根据参数返回其中一个变量。类似以下语句:

public Button getButton(int index) {
    switch (index) {
        case 0: return button0;
        case 1: return button1;
        ...
        default: throw new ArgumentOutOfRangeException("index");
    }
}

然后你可以用下面的东西替换你的循环:

for (int x = 1; x < 10; x++)
    mm.add((Button) findViewById(R.id.getButton(x)));

int[] imageButtons = { R.id.imageButton0, R.id.imageButton1, R.id.imageButton2, R.id.imageButton3, ...};
for (int x = 0; x <9; x++)
mm.add((Button) findViewById(imageButtons[i]));

这应该可以正常工作。:)

最新更新