Compose中基于可用高度实现垂直滚动视图条件定位的最佳实践
动态内容Scrollable Column底部按钮自适应布局优化
我有一个支持垂直滚动的Column,其中组件可动态增删。需求是:组件未填满屏幕时,按钮固定在屏幕底部;组件填满屏幕时,按钮置于滚动Column的内容下方。我曾实现方案,但在内容高度接近屏幕高度的临界场景表现不佳,寻求更优实现方式。感谢帮助!
BoxWithConstraints { val screenHeight = constraints.maxHeight val contentHeight = remember { mutableStateOf(0) } val bottomLayoutHeight = remember { mutableStateOf(0) } Column( Modifier .fillMaxWidth() .verticalScroll(rememberScrollState()) .onGloballyPositioned { coordinates -> contentHeight.value = coordinates.size.height } .padding(horizontal = Constants.HORIZONTAL_PADDING) ) { // Indefinite views here // ... // If content does not fit within the screen, place the button inside the scrollable column if (contentHeight.value + bottomLayoutHeight.value >= screenHeight) { Column(Modifier.onGloballyPositioned { bottomLayoutHeight.value = it.size.height }) { BottomLayout(viewModel) } } } // If content fits within the screen, place the button outside the scrollable column if (contentHeight.value + bottomLayoutHeight.value < screenHeight) { Column(Modifier .fillMaxSize() .padding(horizontal = Constants.HORIZONTAL_PADDING), verticalArrangement = Arrangement.Bottom ) { Column(Modifier.onGloballyPositioned { bottomLayoutHeight.value = it.size.height }) { BottomLayout(viewModel) } } } }
更新
修改后的代码可完美适配临界场景!此前遗漏了计算底部布局高度并与内容高度相加,以此判断总高度是否超过屏幕高度!^^
内容的提问来源于stack exchange,提问作者Duddie
相关产品推荐
相关产品推荐

