gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:41:34 27 4
gpt4 key购买 nike

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

我为所有可组合项使用一个通用的 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
}
}
)
}
}
}
)

最佳答案

所以我解决了这个问题。由于我使用的是导航库,因此我希望它能够在使用 bottomNavBar 时单击后退按钮时保存可组合状态。但我所要做的就是覆盖可组合项内的后退按钮按下并添加一个函数以使用 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
}

关于android-jetpack - 在 Jetpack Compose 中按下后退按钮时滚动位置丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68049300/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com