简体   繁体   中英

How to pass an image from one composable function to another in Jetpack Compose?

I am developing an app with texts and images. The images appear small, like thumbnails, on one composable (activity), alongside the text. The idea is: when the user touches (clicks) the image, the navigation component takes the user to a full screen version of this image in another composable (activity). Is it at al possible? If yes, how? Thanks in advance.

Instead of passing the image itself, you should pass something to identify the image. For instance:

  • If you're loading the image from the resource folder, you should pass the resource ID (ie R.drawable.your_image );
  • If you're using the assets folder or some remote URL, you should pass the image Uri (ie /path_in_assets/your_image or https://foo.bar/your_image ).

Then from the "ListActivity" you can pass the image ID to next activity using the Intent extras.

startActivity(
    Intent(context, DetailsActivity::class.java).apply {
        putExtra("imageId", yourImageId) // resource ID or image URL
    }
)

in "DetailsActivity", inside of the onCreate method, you will get image ID and load it properly...

class DetailsActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // for uri ID
        val imageId = intent.getStringExtra("imageId")
        // for resource ID
        val imageId = intent.getIntExtra("imageId", -1)

        setContent {
            YourAppTheme {
                YourScreen(imageId)
            }
        }
    }
}

finally, in your composable, you can load an image based on resource ID using:

Image(painter = painterResource(id = imageId), contentDescription = null)

or using Coil for URL resource:

Image(painter = rememberAsyncImagePainter(imageId), contentDescription = null)

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