Martin Göpfert
Martin Göpfert

Reputation: 17

how to create dynamic setImageResource

How can I replace something like:

when (content[position].ImageSrc) {
            1 ->  holder.imageView.setImageResource(R.drawable.image_1)
            2 ->  holder.imageView.setImageResource(R.drawable.image_2)
            3 ->  holder.imageView.setImageResource(R.drawable.image_3)

            else -> { 
                holder.imageView.setImageResource(R.drawable.image_x)
            }
        }

more elegant so something like:

var a = "image_"
var b = content[position].ImageSrc
var c = a + b
holder.imageView.setImageResource(R.drawable.c)

The first code is working but way to laborious, the second one isn't. Thx:)

Upvotes: 0

Views: 129

Answers (3)

Rajan Kali
Rajan Kali

Reputation: 12953

val imageId = resources.getIdentifier("com.packagename.app:drawable/image_${content[position].ImageSrc}", null, null);
holder.imageView.setImageResource(imageId)

Upvotes: 0

Martin Marconcini
Martin Marconcini

Reputation: 27236

Make a Repository that can resolve the asset for you...

in your UI you'd do:

holder.imageView.setImageResource(
       myResourceRepo.getImageResourceFor(content[position].ImageSrc)
)

Now what you do in there, it really depends, if you really have 100 resources, you have to find a way to MAP them together, either by creating a mapOf(Int, "img source") (whatever that is), where Int is the R.drawable.xxx and img source is whatever is in content[...].imageSrc (a String?)

This is how you map/associate them together.

If you want it to be more dynamic, then store your images in "raw assets" and using the AssetManager, load the image and convert it into a Drawable at runtime. This way you get to "construct" the asset name like you did

var filename = "some/path/" + content[...].imageSrc

val file = assetManager.open(filename)...
val drawable = makeDrawableFrom(file)

return drawable

Your viewHolder will then use it as

val drawable = repo.getDrawableFrom(content[x].imageSrc)
holder.imageView.setImageResource(drawable)

(NOTE: most of these are "pseudo-code", you have to implement most of it, but it's all possible and quite simple).

If you REALLY want to try to load a resource dynamically... it used to be possible with something like

val nameOfResource = "a" + "b" + "c" //construct your "dynamic" name
val drawable = context.resources.getIdentifier(nameOfResource,
                "drawable", context.getPackageName())

(not sure if this still works)

Upvotes: 2

Dhanuesh
Dhanuesh

Reputation: 1596

I doubt your "second method" exist instead, you can reformat your first one as follows,

holder.imageView.setImageResource(
when (content[position].ImageSrc) {
            1 ->  R.drawable.image_1
            2 ->  R.drawable.image_2
            3 ->  R.drawable.image_3
            else ->R.drawable.image_else
        }
)

Upvotes: 0

Related Questions