I have an int, int minion1Hp
, which can be a value of 0 -> 20. Depending on the value it is, a certain image resource will be set for an ImageView
, using bar1.setImageResource(R.drawable.hpa);
. However, my code currently looks like this:
if (minion1Hp == 0) {
bar1.setImageResource(R.drawable.hp);
}
if (minion1Hp == 1) {
bar1.setImageResource(R.drawable.hpa);
}
if (minion1Hp == 2) {
bar1.setImageResource(R.drawable.hpb);
}
if (minion1Hp == 3) {
bar1.setImageResource(R.drawable.hpc);
}
if (minion1Hp == 4) {
bar1.setImageResource(R.drawable.hpd);
}
if (minion1Hp == 5) {
bar1.setImageResource(R.drawable.hpe);
}
... and so on. Is there a more efficient way of doing this, rather than a long list of if
statements?
Suggestion: initialize a map at startup (say in onCreate()
). Like this:
mDrawables = new HashMap<Integer, Integer>();
mDrawables.put(0, R.drawable.hp);
mDrawables.put(1, R.drawable.hpa);
...
then just do:
bar1.setImageResource(mDrawables.get(minion1Hp));
You can use a switch
statement with a separate case
for each instance. On a side note, you shouldn't be using just if
statements up there, your code will run slowly, you should be using else if
to make it run faster (since your hp
can never be 1 and 2 at the same time.
Ex for switch statements:
switch (minion1Hp){ case 1: bar1.setImageResource(R.drawable.hp); break; case 2: bar1.setImageResource(R.drawable.hpa); break;
etc.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
这里的改进是改变每个if
第一个到后else if
为minion1Hp
不能在同一时间多个值,但你可能会发现它稍微整洁有在整个事情switch-case
块来代替。
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.