Home > Software engineering >  With R.drawable.test, can test be changed using a for loop?
With R.drawable.test, can test be changed using a for loop?

Time:06-19

I am trying to make it so that if a char is '1' then a drawable image of 1 will be shown. If the char is '2' then a 2 image will display.

This will 100% work but it's inefficient

These two are the general idea, but it doesn't work

CodePudding user response:

You could reduce the used ifs and cleanup the code of the first example. Then you do not have to duplicate the if statements (have a look at the DRY principle).

However, you still need a separate drawable for every number:

val mapping = mapOf(
   "1" to R.drawable.rating1,
   "2" to R.drawable.rating2,
   "3" to R.drawable.rating3,
   "4" to R.drawable.rating4,
   ...
   "10" to R.drawable.rating10,
)

val number = parseItem.getImageUrl().charAt(34)
val drawableId = mapping[number]

Picasso
    .get()
    .load(drawableUrl)
    .fit()
    .centerInside()
    .into(holder.imageView)

CodePudding user response:

Use"R.drawable.rating "String.valueOf(i) ".png"

Instead of "R.drawable.rating1.png" in your second attempt

Or just use a switch statement instead.

Let me know if you want switch statement explained

  • Related