Jetpack Compose:ModalBottomSheet的expand()为何为internal?如何调用?
问题
在使用ModalBottomSheet时,发现sheetState提供了show()和hide()两个公开方法。其中show()的文档及实现如下:
/** * Show the bottom sheet with animation and suspend until it's shown. If the sheet is taller * than 50% of the parent's height, the bottom sheet will be half expanded. Otherwise it will be * fully expanded. * * @throws [CancellationException] if the animation is interrupted */ suspend fun show() { val targetValue = when { hasHalfExpandedState -> HalfExpanded else -> Expanded } animateTo(targetValue = targetValue) }
但仅调用sheetState.show()时,偶尔会出现底部弹窗半展开的情况,导致UI不一致。查看源码后发现有一个expand()内部方法正是我需要的:
/** * Fully expand the bottom sheet with animation and suspend until it if fully expanded or * animation has been cancelled. * * * @throws [CancellationException] if the animation is interrupted */ internal suspend fun expand() = animateTo(Expanded)
但该方法是internal修饰的,无法从外部访问。请问有没有办法通过sheetState强制将底部弹窗切换到完全展开状态?
解决方法
你可以直接调用sheetState的公开方法animateTo(Expanded)来实现强制完全展开的效果,这和内部的expand()方法逻辑完全一致。
示例代码:
// 在协程作用域内调用 coroutineScope.launch { sheetState.animateTo(ModalBottomSheetValue.Expanded) }
另外,如果你希望从根源上避免半展开状态,可以在创建ModalBottomSheetState时,设置skipHalfExpanded = true,这样show()方法会直接将弹窗完全展开:
val sheetState = rememberModalBottomSheetState( initialValue = ModalBottomSheetValue.Hidden, skipHalfExpanded = true )
这种方式更适合全局需要禁用半展开的场景,无需每次调用都手动指定展开状态。
内容的提问来源于stack exchange,提问作者Gastón Saillán
相关产品推荐
相关产品推荐

