|

How to add an Image Button in Android Jetpack Compose

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.

There is already 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 Jetpack 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()
    }
}

In the code above, our image is embedded in a box to maintain its shape. Always remember to add an appropriate content description for accessibility purposes.

And there you have it, an image button in Android Jetpack Compose, brought to life using the power of modifiers! I hope this tutorial helps you add more interactivity to your Jetpack Compose applications.

Similar Posts

Leave a Reply