androidkotlinandroid-jetpack-composefloating-action-buttonandroid-compose-button

Jetpack Compose: How to disable FloatingAction Button?


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?


Solution

  • 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)
    }