Home > Back-end >  Kotlin/Android, is there any way to simplify multiple resource references?
Kotlin/Android, is there any way to simplify multiple resource references?

Time:10-03

I'm new to Kotlin, and I've just started refactoring my code. These parts of my code are painful to look at. Problem is, these are from my resources so I can't really figure out a way to just loop it.

paintingList.add(findViewById(R.id.painting1))
paintingList.add(findViewById(R.id.painting2))
paintingList.add(findViewById(R.id.painting3))
paintingList.add(findViewById(R.id.painting4))
paintingList.add(findViewById(R.id.painting5))
paintingList.add(findViewById(R.id.painting6))

or

when (paintingModels.paintings[i].type) {
1 -> paintingList[i].setImageResource(R.drawable.painting1)
2 -> paintingList[i].setImageResource(R.drawable.painting2)
3 -> paintingList[i].setImageResource(R.drawable.painting3)
4 -> paintingList[i].setImageResource(R.drawable.painting4)
5 -> paintingList[i].setImageResource(R.drawable.painting5)
6 -> paintingList[i].setImageResource(R.drawable.painting6)
                    }

What is the way to solve this? Or is this just something that Kotlin devs have to live with?

CodePudding user response:

  val resourceIds = listOf(R.id.painting1, R.id.painting2, R.id.painting3)// continue for all resources

Or even

  val imageViews = listOf(R.id.painting1, R.id.painting2, R.id.painting3).map { findViewById(it) }

That would simplify #1

CodePudding user response:

This might work for you:

for (i in 1..6) {
    paintingList.add(findViewById(resources.getIdentifier("painting$i", "id", packageName)))
}
  • Related