Search code examples
androidandroid-jetpack-composeandroid-jetpack-navigation

How to prevent LazyColumn reset position in Jetpack compose when navigating between bottom nav tabs?


@Composable
fun HomeScreen(){
    val popularListState = rememberLazyListState()
    val viewModel: HomeViewModel = hiltNavGraphViewModel()
    val popularMovies: List<Movie> by viewModel.popularMoviesLiveData.observeAsState(emptyList())
    LazyColumn(
        state = popularListState
    ) {
        itemsIndexed(movies) { _, movie ->
            HomeMovieComponent(movie = movie)
        }
    }
}

Whenever navigate to other screen from the bottom nav the lazy column resets the scroll position to top

Followed this guide to setup the bottom nav


Solution

  • Whenever you select BottomNavigationItem your composable replaced by other composable and when you select back it reinitializes again. To restore previous composable use saveState = true and restoreState = true in your BottomNavigationItem.

    BottomNavigationItem(
        icon = { /*Some Icon*/ },
        label = { /*Some Text*/ },
        selected = currentRoute == item.route,
        onClick = {
          navController.navigate(item.route) {
            // Put These line in your code.
            popUpTo(navController.graph.startDestinationId) {
              saveState = true
            }
            launchSingleTop = true
            restoreState = true
          }
      }
    )