how to bind drawable files to variables - Kotlin

Viewed 137

I'm developing an app which needs to set some wallpapers on the phone from my drawables folder, but I have to write code for each file separately. this is my code:

    fun setWallpaper(number:Int) {

  val wallpaperManager = WallpaperManager.getInstance(context)
  val i: Int = when(number){
      0->R.drawable.wp1.toInt()
      1->R.drawable.wp2.toInt()
      2->R.drawable.wp3.toInt()
      3->R.drawable.wp4.toInt()
      4->R.drawable.wp5.toInt()
      5->R.drawable.wp6.toInt()
      6->R.drawable.wp7.toInt()
      7->R.drawable.wp8.toInt()
      8->R.drawable.wp9.toInt()
      9->R.drawable.wp10.toInt()
      else->0
  }
   wallpaperManager.setResource(i)
 
}

the number variable is the position I get from recyclerview. but this does not seem like a good way and is not dynamic, I can't write a line of code for each file when I have 100 files or so is there a way that I can use to kinda connect a variable to filenames? how can I do it? thanks a lot

1 Answers

You can use listOf and then retrieve by index. There's no reason to use toInt() on each element because they already are Ints. You can import the members of R.drawable using * so don't have to retype it.

import com.mypackage.myapp.R.drawable.*

//...

fun setWallpaper(number: Int) {
  val wallpapers = listOf(wp1, wp2, wp3, /* ... */ wp10)
  val resource = if (number in wallpapers.indices) wallpapers[number] else 0
  WallpaperManager.getInstance(context).setResource(resource)
}

If you have very many of them and a consistent naming scheme, then you can retrieve by name. This is slightly slower because it uses reflection under the hood, but that's trivial to retrieve only one element.

fun setWallpaper(number: Int) {
  val resource = context.resources.getIdentifier("wp${number + 1}", "drawable", context.packageName)
  WallpaperManager.getInstance(context).setResource(resource)
}
Related