In Jetpack Compose, there isn’t a direct ImageButton
component like in the traditional Android View system. Instead, you can combine an Image
and a Button
or use IconButton
with an Image
to achieve similar functionality.
Example 1: ImageButton with Click Action
@Composable
fun ImageButtonExample() {
Button(
onClick = { /* Perform your action */ },
modifier = Modifier.size(100.dp),
shape = CircleShape, // Optional: Circular button
colors = ButtonDefaults.buttonColors(backgroundColor = Color.LightGray) // Optional: Button color
) {
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = "Image Button",
modifier = Modifier.size(50.dp) // Size of the image inside the button
)
}
}
Example 2: ImageButton with IconButton
IconButton
is a lightweight alternative to a full Button
and is ideal for clickable icons or images.
@Composable
fun IconImageButtonExample() {
IconButton(
onClick = { /* Perform your action */ },
modifier = Modifier.size(60.dp)
) {
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = "Icon Button",
modifier = Modifier.size(40.dp) // Size of the image
)
}
}
Example 3: ImageButton with Background and Ripple Effect
@Composable
fun CustomImageButtonExample() {
Box(
modifier = Modifier
.size(80.dp)
.clip(CircleShape) // Shape of the button
.background(Color.LightGray) // Background color
.clickable { /* Perform your action */ },
contentAlignment = Alignment.Center // Align the image to the center
) {
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = "Custom Image Button",
modifier = Modifier.size(50.dp)
)
}
}
Example 4: ImageButton with URL Image Using Coil
If the image source is a URL, you can use Coil to load it dynamically.
- Add Coil dependency:
implementation "io.coil-kt:coil-compose:2.3.0"
- Use it in your composable:
import coil.compose.rememberAsyncImagePainter
@Composable
fun CoilImageButtonExample() {
IconButton(
onClick = { /* Perform your action */ },
modifier = Modifier.size(60.dp)
) {
Image(
painter = rememberAsyncImagePainter(model = "https://via.placeholder.com/300"),
contentDescription = "Image Button",
modifier = Modifier.size(40.dp)
)
}
}
Example 5: ImageButton with Text Below
@Composable
fun ImageButtonWithText() {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.clickable { /* Perform your action */ }
) {
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = "Image Button",
modifier = Modifier.size(50.dp)
)
Text(
text = "Click Me",
style = MaterialTheme.typography.body1,
modifier = Modifier.padding(top = 8.dp)
)
}
}
Key Features:
- Customizable: Use
IconButton
,Box
, orButton
to create the desired appearance and functionality. - Shape and Background: Customize using
Modifier.clip()
andModifier.background()
. - Dynamic Images: Use Coil for images from URLs.
Let me know if you need further examples or modifications! š