How to add an Image Button in Android Jetpack Compose

By Mohammed Rashid •  August 29th, 2022 • 

Jetpack compose provides modifiers for different purposes such as styling components, processing inputs, etc. In this blog post, let’s see how to make an Image Button using modifiers in Android Jetpack Compose.

I already have a tutorial on how to add a button in Jetpack Compose. What we are going to do is to make the Image clickable. We use Modifier.clickable to accomplish the purpose. See the code snippet given below.

Image(painter = painterResource(id = R.drawable.dog), contentDescription = null,
        modifier = Modifier.clickable { println("Button Clicked!") })

Following is the complete example to make an image clickable in Android Compose.

package com.example.example

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import com.example.example.ui.theme.ExampleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    buttonExample()
                }
            }
        }
    }
}

@Composable
fun buttonExample() {
    Box() {
        Image(painter = painterResource(id = R.drawable.dog), contentDescription = null,
        modifier = Modifier.clickable { println("Button Clicked!") })
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ExampleTheme {
        buttonExample()
    }
}

That’s it. Thank you for reading!

Mohammed Rashid

Keep Reading