在Jetpack Compose中按下后退按钮时,滚动位置丢失



我使用底部导航栏,每个菜单都将用户导航到特定的可组合屏幕。我已经使用导航库来管理它们之间的导航。

我正在为所有的可组合使用一个通用的ViewModel。我在其中一个组合中使用了一个惰性列,当我通过单击底部导航栏中的菜单项在菜单项之间导航时,惰性列的滚动位置将按预期进行保存。

当我在有lazyColumn的可组合屏幕中单击按钮(我已对该按钮进行编程,以导航到导航图中的起始目的地(并导航回该按钮时,问题就会出现,然后滚动位置会刷新为0。这是一个错误还是我做错了什么

这是我的代码:

导航

@Composable
fun PopulateHomeComposables(navController: NavHostController,             
homeViewModel: HomeViewModel, lifecycleScope : LifecycleCoroutineScope) {
NavHost(navController = navController, startDestination = 
WHATS_NEW_COMPOSABLE) {
composable(WHATS_NEW_COMPOSABLE) {
WhatsNewComposable(navController)
}
composable(COMPLIMENTS_COMPOSABLE) {
ComplimentsComposable(navController)
}
composable(INSIGHTS_COMPOSABLE) {
InsightsComposable(navController)
}
composable(NOTIFICATIONS_COMPOSABLE) {
NotificationsComposable(homeViewModel, lifecycleScope)
}
}
}

我的脚手架看起来像

Scaffold(
topBar = {
},
content = {
},
floatingActionButton = {
},
bottomBar = {
val items = listOf(BottomNavScreens.WhatsNew, 
BottomNavScreens.Compliments, BottomNavScreens.Insights, 
BottomNavScreens.Notifications)
BottomNavigation {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
//draw the menu items for each one
items.forEach {
BottomNavigationItem(
icon = {
Icon(it.icon, it.label)
},
label = {
Text(it.label)
},
alwaysShowLabel = true,
selected = currentRoute == it.route,
onClick = {
navController.navigate(it.route) {
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
// on the back stack as users select items

navController.graph.startDestinationRoute?.let { route ->
popUpTo(route) {
saveState = true
}
}
//Avoid multiple copies of the same estination when
//re selecting the same item
launchSingleTop = true
//Restore state when re selecting a previously selected item
restoreState = true
}
}
)
}
}
}
)

所以我解决了这个问题。由于我使用的是导航库,我希望它在使用底部NavBar时单击后退按钮时能够保存可组合状态。但我所要做的就是覆盖可组合文件中的后退按钮,并添加一个使用navHostController导航到起始目的地的功能。

//override the back button press to navigate back to the 
//whatsNewComposable
BackHandler {
Timber.i("Back button clicked in notifications composable")
navController.navigate("myStartDestinationRoute) {
// Pop up to the start destination of the graph to
// avoid building up a large stack of destinations
// on the back stack as users select items
navController.graph.startDestinationRoute?.let { route ->
popUpTo(route) {
saveState = true
}
}
//Avoid multiple copies of the same destination when
//re selecting the same item
launchSingleTop = true
//Restore state when re selecting a previously selected item
restoreState = true
}

相关内容

  • 没有找到相关文章

最新更新