[英]How to dynamically address vars with a string?
來自Actionscript 3,Java似乎有點不同:
有三個按鈕,按鈕btn0; 按鈕btn1; 按鈕btn2; 我想迭代它們像這樣設置onClickListeners():
for (int i=0; i < 4; i++) {
this["btn"+i].setOnClickListener(this);
}
甚至可能嗎?
基本上,您在詢問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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.