如何使用字符串动态地解决变量?

时间:2013-11-06 17:15:19

标签: java android

来自Actionscript 3,Java似乎有点不同:

有三个按钮,按钮btn0;按钮btn1;按钮btn2; 我想迭代它们设置onClickListeners(),如下所示:

for (int i=0; i < 4; i++) {    
    this["btn"+i].setOnClickListener(this);
}

甚至可能吗?

1 个答案:

答案 0 :(得分:3)

基本上,您在询问Java中可用的数据结构,让我们看一些选项。如果您使用Map

,则可以在代码中重现该行为
// instantiate the map
Map<String, Button> map = new HashMap<String, Button>();
// fill the map
map.put("btn0", new Button());
// later on, retrieve the button given its name
map.get("btn" + i).setOnClickListener(this);

或者,你可以简单地使用索引作为标识符,在这种情况下最好使用List

// instantiate the list
List<Button> list = new ArrayList<Button>();
// fill the list
list.add(new Button());
// later on, retrieve the button given its index
list.get(i).setOnClickListener(this);

或者如果按钮数量是固定的并且事先已知,请使用数组:

// instantiate the array
Button[] array = new Button[3];
// fill the array
array[0] = new Button();
// later on, retrieve the button given its index
array[i].setOnClickListener(this);