Add drawer toggle button in Jetpack compose
Asked Answered
V

2

14

I want to add the hamburger icon to the Appbar and open/close drawer using the icon.

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

Ventris answered 4/9, 2020 at 9:36 Comment(0)
V
16

Use rememberScaffoldState() to modify drawer state.

  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(
   scaffoldState = state,
   // ...
)
  1. Use state.drawerState.open() or state.drawerState.close() in an onClick to open/close the drawer.

  2. Create an Icon for navigationIcon in TopAppBar:

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
}
Ventris answered 4/9, 2020 at 11:27 Comment(4)
What does rememberScaffoldState does?Malliemallin
It's an internal state in the Scaffold composable. ReferenceVentris
what is "it"???Jair
Been a long time. But I think state.drawerStateVentris
P
12

You can use:

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

enter image description here

Photophilous answered 13/3, 2021 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.