How to make Jetpack compose IconButton's width to adapt children's width?
Asked Answered
V

2

5

I want to make an IconButton with text below the icon. I have tried applying those width-related methods in Modifier to all the IconButton, Column, Icon and Text. The code below the is closest I got. The result looks like this. And this is what I want to achieve.

@Composable
fun IconButtonWithTextBelow(
    title: String,
    @DrawableRes imageId: Int,
    onClick: () -> Unit
) {
    IconButton(
        onClick = onClick,
        modifier = Modifier.requiredWidth(IntrinsicSize.Max)
    ) {
        Column(
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.requiredWidth(IntrinsicSize.Max)
        ) {
            Icon(
                painter = painterResource(id = imageId),
                contentDescription = title,
            )
            Text(
                text = title,
            )
        }
    }
}
Vaquero answered 4/9, 2021 at 12:40 Comment(0)
T
9

As the name IconButton implies, it is only for displaying Icon. Even if you increase the size of the container with a static size modifier, you will find that the ripple when you click it is still too small.

You can use TextButton, I will work fine with Icon + Text, you just need to specify contentColor: IconButton uses LocalContentColor.current by default, so you can use that too.

TextButton(
    onClick = { /*TODO*/ },
    colors = ButtonDefaults.textButtonColors(contentColor = LocalContentColor.current)
) {
    Column(
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
    ) {
        Icon(
            painter = painterResource(id = imageId),
            contentDescription = title,
        )
        Text(
            text = title,
        )
    }
}

But the implementation of TextButton may change in the future, the name says only about Text after all.

So a better option would be to just use the clickable modifier on your Column, and maybe padding. The result will be pretty much the same.

Column(
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally,
    modifier = Modifier
        .padding(10.dp)
        .clickable(
            onClick = onClick,
            role = Role.Button,
        )
) {
    Icon(
        painter = painterResource(id = imageId),
        contentDescription = title,
    )
    Text(
        text = title,
    )
}

Tonsillotomy answered 4/9, 2021 at 13:4 Comment(0)
C
5

IconButton's size restricted with 48.dp so you need to implement your own IconButton. You can check source code of IconButton.

Clermontferrand answered 4/9, 2021 at 13:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.