简体   繁体   中英

How to dynamically address vars with a string?

Comming from Actionscript 3, Java seems to be a bit different here:

Having three Buttons, Button btn0; Button btn1; Button btn2; I want to iterate through them setting onClickListeners() like this:

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

is that even possible?

Basically, you're asking about the data structures available in Java, let's see some options. It's possible to reproduce the behavior in your code if you use a 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);

Alternatively, you could simply use the index as identifier, in which case it's better to use a 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);

Or if the number of buttons is fixed and known beforehand, use an array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM