使 ModalBottomSheetLayout 始终展开

Mar*_*rat 17 android android-jetpack-compose

ModalBottomSheetLayout我在 Jetpack Compose 中使用。每当它显示为 时modalBottomSheetState.show(),它都会显示HalfExpanded或 ,Expanded具体取决于其内容的高度。这是来自源代码:

val anchors = if (sheetHeight < fullHeight / 2) {
        mapOf(
            fullHeight to Hidden,
            fullHeight - sheetHeight to Expanded
        )
    } else {
        mapOf(
            fullHeight to Hidden,
            fullHeight / 2 to HalfExpanded,
            max(0f, fullHeight - sheetHeight) to Expanded
        )
    }
    Modifier.swipeable(
        state = sheetState,
        anchors = anchors,
        orientation = Orientation.Vertical,
        enabled = sheetState.currentValue != Hidden,
        resistance = null
    )
Run Code Online (Sandbox Code Playgroud)

然后show()像这里一样工作:

 internal val isHalfExpandedEnabled: Boolean
    get() = anchors.values.contains(HalfExpanded)

/**
 * Show the bottom sheet with animation and suspend until it's shown. If half expand is
 * enabled, 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 =
        if (isHalfExpandedEnabled) HalfExpanded
        else Expanded
    animateTo(targetValue = targetValue)
}
Run Code Online (Sandbox Code Playgroud)

我想知道我们是否可以将其设置为Expanded始终

Gab*_*tti 37

您可以使用:

scope.launch { state.animateTo(ModalBottomSheetValue.Expanded) }
Run Code Online (Sandbox Code Playgroud)

代替

scope.launch { state.show() }
Run Code Online (Sandbox Code Playgroud)

从 compose 开始,1.2您可以使用该skipHalfExpanded属性:

跳过半展开:如果为 true,则工作表将始终展开到“展开”状态,并在隐藏工作表时以编程方式或通过用户交互移动到“隐藏”状态

就像是:

var skipHalfExpanded by remember { mutableStateOf(true) }
val state = rememberModalBottomSheetState(
    initialValue = ModalBottomSheetValue.Hidden,
    skipHalfExpanded = skipHalfExpanded
)
Run Code Online (Sandbox Code Playgroud)


小智 14

使用:

bottomSheetState.animateTo(ModalBottomSheetValue.Expanded)
Run Code Online (Sandbox Code Playgroud)

显示展开的工作表

使用confirmStateChange

 val bottomSheetState =
        rememberModalBottomSheetState(ModalBottomSheetValue.Hidden, confirmStateChange = {
            it != ModalBottomSheetValue.HalfExpanded
        })
Run Code Online (Sandbox Code Playgroud)

以避免板材半展开


ula*_*gor 10

使用skipHalfExpanded

val bottomSheetStatus =
    rememberModalBottomSheetState(
        ModalBottomSheetValue.Hidden,
        skipHalfExpanded = true,
    )
Run Code Online (Sandbox Code Playgroud)

  • 需要明确的是:此方法仅适用于目前处于 alpha 阶段的 Compose 1.2 或更高版本。对于 1.1 或更低版本,这个答案 /sf/answers/4846258161/ 是一个很好的方法。 (3认同)