'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.
Solution 1:[1]
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 (i.e.
R.drawable.your_image
); - If you're using the
assets
folder or some remote URL, you should pass the imageUri
(i.e./path_in_assets/your_image
orhttps://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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |