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

Add drawer toggle button in Jetpack compose

我想使用该图标将汉堡包图标添加到 Appbar 和 open/close 抽屉。

我该如何实现?

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") }
      )
    },
  ) {}

使用rememberScaffoldState()修改抽屉状态

  1. 创建一个变量:
val state = rememberScaffoldState()
val scope = rememberCoroutineScope() // in 1.0.0-beta `open()` and `close` are suspend functions
  1. 将状态传递给Scaffold
Scaffold(
   scaffoldState = state,
   // ...
)
  1. onClick到open/close抽屉中使用state.drawerState.open()state.drawerState.close()

  2. TopAppBar 中为 navigationIcon 创建图标:

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
}

使用 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()
    })