Search code examples
androidandroid-drawable

With R.drawable.test, can test be changed using a for loop?


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


Solution

  • 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)