How to add an image to a button in jetpack compose/kotlin – Kotlin

by
Alexei Petrov
android android-jetpack-compose gradle-kotlin-dsl jetpack-compose-navigation

Quick Fix: In the Button’s Image parameter, you should pass the ImageResource instead of the Image. You can use ImageResource(painter = painterResource(id = imageRes)) to specify the drawable.

The Problem:

In Jetpack Compose, a custom button component called ‘DefaultButton’ is created. The goal is to add an image to this button, but attempts to pass an image as a parameter have been unsuccessful. Is there an alternative approach to achieve this or a different way to incorporate an image into the button? Additionally, can the ‘icon’ modifier be utilized instead, and if so, what are the key differences between ‘image’ and ‘icon’?

The Solutions:

Solution 1: Using @DrawableRes and Image

To add an image to a button in a composable function, you can use the @DrawableRes annotation. Here’s how:

  1. Add the @DrawableRes annotation to the image parameter:
fun DefaultButton(
    @DrawableRes image: Int,
    text: String,
    onClick: () -> Unit
) {
    ...
}
  1. To add the image to the button, use the Image composable:
Image(
    painter = PainterResource(id = image),
    modifier = modifier.size(50.dp)
)

For example, to add the "ic_favorite" drawable to the button, you would do this:

DefaultButton(
    image = R.drawable.ic_favorite,
    text = "Like",
    onClick = {}
)

This will add the "ic_favorite" drawable to the left of the button’s text. You can adjust the size and position of the image using the modifier parameter.

Q&A

Is it possible to add an image as a parameter to a function?

Yes, you can add an ImageVector or a Painter as a parameter.

How can you add an image to a button without adding it as a parameter?

You can use the icon parameter in the Button composable.

What’s the difference between icon and image?

The icon parameter takes an ImageVector or a Painter, while the image parameter takes an Image.

Video Explanation:

The following video, titled "The Jetpack Compose Beginner Crash Course for 2023 (Android ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

How to Create Your First App in Compose Multiplatform ... The Circuit – Compose-driven Architecture for Kotlin and Android | Talking Kotlin #121.