简体   繁体   English

在 Jetpack compose 中添加抽屉切换按钮

[英]Add drawer toggle button in Jetpack compose

I want to add the hamburger icon to the Appbar and open/close drawer using the icon.我想将汉堡包图标添加到 Appbar 并使用该图标打开/关闭抽屉。

How would I achieve this?我将如何实现这一目标?

Scaffold(
    drawerShape = RoundedCornerShape(topRight = 10.dp, bottomRight = 10.dp),
    drawerElevation = 5.dp,
    drawerContent = {
      // Drawer
    },
    topBar = {
      TopAppBar(
        navigationIcon = {
          Icon(
            Icons.Default.Menu,
            modifier = Modifier.clickable(onClick = {
              // Open drawer => How?
            })
          )
        },

        modifier = Modifier
          .fillMaxWidth()
          .clip(RoundedCornerShape(bottomLeft = 10.dp, bottomRight = 10.dp)),
        title = { Text(text = "Hello") }
      )
    },
  ) {}

Use rememberScaffoldState() to modify drawer state.使用rememberScaffoldState()修改抽屉状态。

  1. create a variable:创建一个变量:
val state = rememberScaffoldState()
val scope = rememberCoroutineScope() // in 1.0.0-beta `open()` and `close` are suspend functions
  1. Pass the state to Scaffold将状态传递给Scaffold
Scaffold(
   scaffoldState = state,
   // ...
)
  1. Use state.drawerState.open() or state.drawerState.close() in an onClick to open/close the drawer.onClick使用state.drawerState.open()state.drawerState.close()来打开/关闭抽屉。

  2. Create an Icon for navigationIcon in TopAppBar :TopAppBarnavigationIcon创建一个图标:

val state = rememberScaffoldState()
Scaffold(
  scaffoldState = state,
  topBar = {
    TopAppBar(
      title = { Text(text = "AppBar") },
      navigationIcon = {
        Icon(
          Icons.Default.Menu,
          modifier = Modifier.clickable(onClick = {
            scope.launch { if(it.isClosed) it.open() else it.close() }
          })
        )
      }
    )
  },
  drawerShape = RoundedCornerShape(topRight = 10.dp, bottomRight = 10.dp),
  drawerContent = {
    Text(text = "Drawer")
  }
) {
   // Scaffold body
}

With the 1.0.0 (tested with 1.0.0-beta07 ) you can use:使用1.0.0 (使用1.0.0-beta07测试),您可以使用:

val scaffoldState = rememberScaffoldState()
val scope = rememberCoroutineScope()

Scaffold(
    scaffoldState = scaffoldState,
    drawerContent = { Text("Drawer content") },
    topBar = {
        TopAppBar(
           modifier = Modifier
            .clip(RoundedCornerShape(bottomStart = 8.dp, bottomEnd = 8.dp))
        ) {
            IconButton(
                onClick = {
                    scope.launch { scaffoldState.drawerState.open() }
                }
            ) {
                Icon(Icons.Filled.Menu,"")
            }
        }
    },
    content = {
        //bodyContent()
    })

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM