Reputation: 617
How can I change this coding into an array? Because I found this step is too long. I'm new to this so can you help me. Thank you.
if(num2 == 1)
{
display.setImageResource(R.drawable.one);
if (num1 == 1)
{
display2.setImageResource(R.drawable.one);
}
else if (num1 == 2)
{
display2.setImageResource(R.drawable.two);
}
else if (num1 == 3)
{
display2.setImageResource(R.drawable.three);
}
else if (num1 == 4)
{
display2.setImageResource(R.drawable.four);
}
else if (num1 == 5)
{
display2.setImageResource(R.drawable.five);
}
}
Upvotes: 0
Views: 230
Reputation: 67209
One option would be to use a LevelListDrawable
.
You define the Drawable like so:
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:maxLevel="1" android:drawable="@drawable/one />
<item android:maxLevel="2" android:drawable="@drawable/two" />
<item android:maxLevel="3" android:drawable="@drawable/three" />
<!-- ... -->
</level-list>
Either in XML or in your code, set the background of display2
to this Drawable.
You can then simplify your code to:
if(num2 == 1) {
display2.setImageLevel(num1);
}
Upvotes: 0
Reputation: 6230
If you have control over your R
object, I'd strongly advise to simply store the drawable
members as an array to begin with. But if you insist,
Drawable[] drawables = new Drawable[...];
drawables[1] = R.drawable.one;
drawables[2] = R.drawable.two;
...
if(num2 == 1) {
int index = (num1 >= 1 && num1 < drawables.length) ? num1 : 1;
display2.setImageResource(drawables[index]);
}
Although it may be better to just stick to your current code or use switch
. It's verbose, yes, but pretty clear.
Upvotes: 2