Skip to content
DeveloperMemos

@DrawableRes in Jetpack Compose

Jetpack Compose, Android Development, Kotlin1 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.

What is @DrawableRes?

@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.

How to use @DrawableRes in Jetpack Compose

To use @DrawableRes in Jetpack Compose, you can simply annotate an integer parameter with @DrawableRes. For example:

1@Composable
2fun MyImage(@DrawableRes resId: Int) {
3 Image(
4 painter = painterResource(resId),
5 contentDescription = null // TODO: Add content description
6 )
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.

Another Example

Here’s another example of how you can use @DrawableRes in Jetpack Compose:

1@Composable
2fun 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 description
8 )
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.

Wrap Up

  • Jetpack Compose simplifies UI development by combining reactive programming and Kotlin's ease of use.
  • The @DrawableRes annotation is used to indicate a drawable resource reference in Jetpack Compose.
  • It is validated by the Android build tools at compile time.
  • To use @DrawableRes, annotate an integer parameter with @DrawableRes.
  • The painterResource function is used to load the drawable resource and pass it to the Image composable.