— Jetpack Compose, Android Development, Kotlin — 1 min read
Jetpack Compose is a modern toolkit designed to simplify UI development. It combines a reactive programming model with the conciseness and ease of use of the Kotlin programming language. In this post, we will learn how to use the @DrawableRes
annotation in Jetpack Compose to load images from resources.
@DrawableRes
is an annotation that can be used to indicate that an integer parameter, field or method return value is expected to be a drawable resource reference (e.g. R.drawable.my_image
). This annotation is used by the Android build tools to validate that the resource reference is valid at compile time.
To use @DrawableRes
in Jetpack Compose, you can simply annotate an integer parameter with @DrawableRes
. For example:
1@Composable2fun MyImage(@DrawableRes resId: Int) {3 Image(4 painter = painterResource(resId),5 contentDescription = null // TODO: Add content description6 )7}
In this example, we have defined a composable function called MyImage
that takes an integer parameter annotated with @DrawableRes
. We then use the painterResource
function to load the drawable resource and pass it to the Image
composable.
Here’s another example of how you can use @DrawableRes in Jetpack Compose:
1@Composable2fun MyButton(@DrawableRes iconId: Int, text: String) {3 Button(onClick = { /* Do something */ }) {4 Row(verticalAlignment = Alignment.CenterVertically) {5 Image(6 painter = painterResource(iconId),7 contentDescription = null // TODO: Add content description8 )9 Spacer(modifier = Modifier.width(8.dp))10 Text(text)11 }12 }13}
In this example, we have defined a composable function called MyButton that takes an integer parameter annotated with @DrawableRes. We then use the painterResource function to load the drawable resource and pass it to the Image composable.