Search code examples
androidbuttonandroid-jetpack-composelazyvgrid

What is the best way to avoid accidental repeated clicks on Any btn?


My problem was accidentally repeated clicks on LazyVerticalGrid element which is resolved by using:

var enabled by rememberSaveable { mutableStateOf(true) } and val scope = LocalLifecycleOwner.current.lifecycleScope.

LazyVerticalGrid(
        state = lazyVGState,
        cells = GridCells.Fixed(3),
        contentPadding = PaddingValues(bottom = 100.dp)
    ) {
        items(groupMap.keys.toList().sorted()) { item ->
            Column(
                modifier = Modifier.clickable(
                    enabled = enabled,
                ) {
                    enabled = false
                    navController.currentBackStackEntry?.savedStateHandle?.set(
                        CITY_WEATHER_LIST,
                        cityList
                    )
                    navController.navigate(Screen.CityForecastScreen.route)
                    scope.launchWhenStarted {
                        delay(10)
                        enabled = true
                    }
                },

                ) {
                // some elements
            }
        }
    }

If i don't use enabled state, user may open an element for couple times. Looking for community opinion. THX.


Solution

  • The navigation framework provides an up to date and synchronous view of the navigation state in your app, so the safest way to prevent multiple clicks is by checking if you are still in the navigation destination hosting your LazyList by using

    navController.currentDestination
    

    and comparing that against the LazyList screen identifier.