在 Jetpack compose 中使用 ModalDrawer 从右向左打开导航抽屉

Spa*_*tta 15 android navigation-drawer android-jetpack-compose

我一直在尝试在 Jetpack compose 中实现导航抽屉。以下代码显示了一种简单的方法:

@Composable
fun ModalDrawerSample() {
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()

    ModalDrawer(
        drawerState = drawerState,
        drawerContent = {
            Column {
                Text("Text in Drawer")
                Button(onClick = {
                    scope.launch {
                        drawerState.close()
                    }
                }) {
                    Text("Close Drawer")
                }
            }
        },
        content = {
            Column {
                Text("Text in Bodycontext")
                Button(onClick = {

                    scope.launch {
                        drawerState.open()
                    }

                }) {
                    Text("Click to open")
                }
            }
        }
    )
}
Run Code Online (Sandbox Code Playgroud)

但是如何使导航抽屉从右向左打开呢?

Gab*_*tti 19

您可以使用LocalLayoutDirection提供LayoutDirection.Rtl值。

就像是:

CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl ) {
    ModalDrawer(
        drawerState = drawerState,
        drawerContent = { /* ...*/ },
        content = { /* ..*/ }
    )
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 通过在内容参数中另外使用“CompositionLocalProvider(LocalLayoutDirection提供LayoutDirection.Ltr)”解决了这个问题。 (5认同)
  • 这样做也导致我的布局从右到左反转。 (4认同)
  • 我结合了 Gabriele 和 Sparsh 的帖子,发现我需要先用 Column 包装抽屉内容,因为 Rtl 已应用于在引擎盖下使用的 Column。我用迄今为止所拥有的内容创建了一个要点,包括屏幕截图:https://gist.github.com/free2bcreative/7c9befbeaf0b6155b3b83d43af968b01 (4认同)
  • 如何实现左右两个抽屉 (3认同)
  • @Gabriele Mariotti 非常感谢。你救了我的命 :) 2022 年是否有更惯用的方法来做到这一点? (2认同)
  • 这与其说是一个实际的解决方案,不如说是一种黑客攻击。 (2认同)