How to set the Scaffold Drawer Width in JetpackCompose?

7.5k views Asked by At

We can have Navigation Drawer in JetpackCompose by using Scaffold as below

Scaffold(
    drawerContent = { Text(text ="Drawer") }
) {}

enter image description here

I want to make the width of the drawer smaller. How can I do so?

5

There are 5 answers

3
CyrilFind On

Have you tried adding a modifier inside your drawer composable ?

Something like this:

Scaffold(drawerContent = { 
        Box(modifier = Modifier.fillMaxWidth(0.9f){
            Text(text = "Drawer") 
        }
    }) {}
0
Vahe Gharibyan On

Here is an example drawing a Scaffold custom shape.

1. Spec exact size.

Scaffold(
    drawerShape = NavShape(400.dp, 0f)
)

2. Spec size by percent (half screen).

Scaffold(
    drawerShape = NavShape(0.dp, 0.5f)
)

Custom shape class

class NavShape(
    private val widthOffset: Dp,
    private val scale: Float
) : Shape {

    override fun createOutline(
        size: Size,
        layoutDirection: LayoutDirection,
        density: Density
    ): Outline {
        return Outline.Rectangle(
            Rect(
                Offset.Zero,
                Offset(
                    size.width * scale + with(density) { widthOffset.toPx() },
                    size.height
                )
            )
        )
    }
}
0
Bréndal Teixeira On

I accomplished that by:

#1 - Setting to the Drawer's content Modifier a max width:

@Composable
fun MyDrawerContent(){
     Column(Modifier.fillMaxHeight().width(300.dp)) {
          ...
        

#2 - Setting the Scafold's drawer colors to Transparent + no Elevation

Scaffold(
     drawerBackgroundColor = Color.Transparent,
     drawerContentColor = Color.Transparent,
     drawerElevation = 0.dp,
     drawerContent = {
          MyDrawerContent()
     },
     ...

Note: Only problem I faced is if you touch on the transparent area the drawer does not closes as it used to. Siding it to close works perfectly though. It's a workaround...

10
Kofi On

You can modify the shape (including width and height) using drawerShape parameter in Scaffold method.

So for instance

 Scaffold(
    scaffoldState = scaffoldState,
    drawerContent = { Text("Drawer content") },
    drawerShape = customShape(),
    content = {inner padding -> /* Body*/}
)

Then your customShape function

fun customShape() =  object : Shape {
    override fun createOutline(
        size: Size,
        layoutDirection: LayoutDirection,
        density: Density
        ): Outline {
            return Outline.Rectangle(Rect(0f,0f,100f /* width */, 131f /* height */))
     }
 }

You can also use Outline.Rounded to get rounded corners

0
Mohamed Tamer On
Scaffold(
      topBar = {
          topBar()
      },
      scaffoldState = scaffoldState,
      drawerContent = {
          drawer()
      },
      drawerGesturesEnabled = true
  ) { innerPadding ->
      NavigationHost(navController = navController)
  }
}