Android ImageButton setImageResource from variable

I want setImageResource for ImageButton programmatically, based on a variable.

For example: if size = 5, I want setImageResource to be R.drawable.five

    if size=6, I want to setImageResource to R.drawable.six

Unfortunately, I have too many of them, so the if-else or switch gets tired.

Is there a way to achieve something like: R.drawable.size?

Thank you, Chris

+3
source share
2 answers

Store id in array

final int[] imgSizeIds = new int[]{ R.drawable.zero,R.drawable.one,R.drawable.two, .... };

then, 
setImageResource(imgSizeIds [ size ] );

Hooray!

+6
source

Ya StOle is right. Using an int array may solve the problem. You just need to get the incrementer variable to access a specific image

0
source

Source: https://habr.com/ru/post/1754076/


All Articles