17

According to the docs, we can disable the FAB by setting null to its onClick:

onClick - will be called when user clicked on this FAB. The FAB will be disabled when it is null.

When I tried it I stumbled across that the onClick parameter is not nullable,

fabs onclick can not be null

So, how to disable the FAB?

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
chrgue
  • 579
  • 1
  • 6
  • 18
  • 1
    Just do nothing in onClick() method, like this onClick = {} . If you want to disable the ripple effect also then refer to this link. https://stackoverflow.com/questions/66703448/how-to-disable-ripple-effect-when-clicking-in-jetpack-compose – Vaibhav Goyal Aug 19 '21 at 12:32
  • You have misunderstood the doc. Setting `onClick = null` will disable `ExtendedFloatingActionButton` not `FloatingActionButton`. – Alpha 1 Aug 19 '21 at 15:37

1 Answers1

21

Currently (1.x.y) the FloatingActionButton doesn't support the enabled property.

As workaround you can use a Button with a CircleShape.

var enabled by remember { mutableStateOf(false) }
Button(
    onClick = { /* do something */},
    modifier = Modifier.defaultMinSize(minWidth = 56.dp, minHeight = 56.dp),
    enabled = enabled,
    shape = CircleShape

){
    Icon(Icons.Filled.Favorite, contentDescription = "Localized description")
}

If you want to use a FloatingActionButton you can do something like:

var enabled by remember { mutableStateOf(false) }


CompositionLocalProvider(LocalRippleTheme provides
        if (enabled)  LocalRippleTheme.current else NoRippleTheme) {
    FloatingActionButton(
        backgroundColor = if (enabled) MaterialTheme.colors.secondary else Gray,
        onClick = { if (enabled) { /* do something */ } else {} },
    ) {
        Icon(Icons.Filled.Favorite,
            contentDescription = "Localized description",
        tint = if (enabled)
            LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
        else DarkGray)
    }
}

with:

private object NoRippleTheme : RippleTheme {
    @Composable
    override fun defaultColor() = Color.Unspecified

    @Composable
    override fun rippleAlpha(): RippleAlpha = RippleAlpha(0.0f, 0.0f, 0.0f, 0.0f)
}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841