简体   繁体   中英

Jetpack Compose how do i work with images when variable changes?

I use the composable function image. I need to use the specific image depending on the variable it gets. it looks like the code underneath when hardcoded and this works for the specific image.

Image(
       painterResource(id = R.drawable.carrot),
       contentDescription = "carrot",
       )

The problem is i want it to work like the picture below where recipe.image changes depending on what it gets from the database.

Image(
       painterResource(id = recipe.image),
       contentDescription = "recipe.name",    
            )

Somehow it needs the exact path to the drawable that is saved localy.

What i have tried: I've tried to upload R.drawable.carrot directly to the database as an Integer, it saves it as something like 2400440340, when this integer gets into the painterResource it crashes.I've tried to save the "R.drawable.carrot" directly as a string into the database but that don't work either because the painter needs an integer.

The only suggestions i can find to this problem on this site is this answer from 11 years ago:

int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);

I can't seem to find the functions getResources or the getIdentifier.

What i have tried: I've tried to upload R.drawable.carrot directly to the database as an Integer, it saves it as something like 2400440340, when this integer gets into the painterResource it crashes.

It crashes because this Int value in Resources is just a runtime reference, which means if you restart the app, the Resource, for example R.drawable.carrot , gets new referenced. If you want another image in your painterResource , you have to change the value of recipe.name somewhere or you save your image binaries in the database (which is not very performant, I recommend not to do that).

You can load them over assets: If you dont't have an assets folder, creat one in this location: app/src/main/assets/

And then you can access it with a function like this:

    fun getImageFromAssets(imageName: String): Bitmap {
        val imageStream = assets.open(imageName)
        val bitmap = BitmapFactory.decodeStream(imageStream)
        imageStream.close()
        return bitmap
    }

Android Studio will suggest you to "Inline" the variable but don't do that. If you Inline the BitmapFactory at the return point, you close the Stream before you decode it.

You can now simply call the name from the database like:

val image: Bitmap = getImageFromAssets("imageName.jpg")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM