Chris
Chris

Reputation: 3807

Android ImageButton setImageResource from variable

I want to setImageResource for an ImageButton programatically, based on a variable.

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

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

Unfortunately, I have too many of these, so an if-else or switch gets tiring.

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

Thanks Chris

Upvotes: 3

Views: 4796

Answers (2)

st0le
st0le

Reputation: 33545

Store the id's in an array

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

then, 
setImageResource(imgSizeIds [ size ] );

Cheers!

Upvotes: 6

success_anil
success_anil

Reputation: 3658

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

Upvotes: 0

Related Questions