我有一个包含多个LazyRow的LazyColumn。用旧的术语来说,就是嵌套的RecyclerView。
我的问题是,当移动到新的composable (不同的标签)时,LazyColumn不能恢复滚动状态。但是内部LazyRow会恢复它们的状态。
例如,打开主页屏幕,滚动到底部,然后滚动LazyRow结束,然后打开不同的选项卡并再次返回主页选项卡。LazyColumn从顶部开始(不恢复状态),但最后一次LazyRow恢复它的滚动状态。
包含LazyColumn的HomeScreen
@Composable
fun HomeScreen(
homeViewModel: HomeViewModel = hiltViewModel()
) {
val scrollState = rememberLazyListState()
LazyColumn(contentPadding = PaddingValues(vertical = 8.dp),
horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.spacedBy(8.dp),
state = scrollState,
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.background)
) {
items(5) {
TopRatedProducts(homeViewModel = homeViewModel)
}
}
}包含LazyRow的TopRatedProducts
@Composable
fun TopRatedProducts(
homeViewModel: HomeViewModel = hiltViewModel()
) {
val topRatedProducts by rememberFlowWithLifecycle(homeViewModel.topRatedProducts)
.collectAsState(initial = emptyList())
LazyRow(
contentPadding = PaddingValues(horizontal = 8.dp), // Space between start and end
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp), // Space between items
modifier = Modifier
.background(Color.Green)
) {
items(topRatedProducts) {
ProductCardItem(item = it)
}
}
}如何恢复LazyColumn滚动状态?
发布于 2021-08-23 15:41:22
当你想在片段中使用ComposeView时,你应该提到ViewCompositionStrategy。
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return ComposeView(requireContext()).apply {
// Dispose the Composition when viewLifecycleOwner is destroyed
setViewCompositionStrategy(
ViewCompositionStrategy.DisposeOnLifecycleDestroyed(viewLifecycleOwner)
)
setContent {
// content
}
}
}From docs:默认情况下,只要视图从窗口分离,Compose就会处理组合。编写UI视图类型(如ComposeView和AbstractComposeView )使用定义此行为的ViewCompositionStrategy。
默认情况下,Compose使用DisposeOnDetachedFromWindow策略。但是,在使用合成UI视图类型时,在某些情况下可能不需要此默认值:
文档链接:https://developer.android.com/jetpack/compose/interop/interop-apis#composition-strategy
https://stackoverflow.com/questions/68467896
复制相似问题