How to set width and height for NavigationDrawer in Jetpack Compose - android

Right now I am using the Scaffold() composable to create a basic drawer layout. However the drawer is always the same size but I want it with a custom width, taking only 2/3 of the screen size and also a custom height, like a padding top and bottom. This is my code so far:
Scaffold(
scaffoldState = state,
topBar = {
TopAppBar(
title = {
SearchBar()
},
navigationIcon = {
IconButton(onClick = {
coroutineScope.launch { state.drawerState.open() }
}) {
Icon(Icons.Default.Menu, contentDescription = null)
}
},
backgroundColor = MaterialTheme.colors.background
)
},
drawerShape = RoundedCornerShape(topEnd = 16.dp, bottomEnd = 16.dp),
drawerContent = { NavigationDrawer(state, coroutineScope) },
content = {
MapScreen(
)
}
)
Changing anything in my composable function NavigationDrawer() won't change anything. Is there any way to achieve this in jetpack compose?

So there is a private val in Drawer which is the problem EndDrawerPadding = 56.dp
On tablets you would want a much larger amount of padding.
Since this can't be changed the best solution I could come up with was to make the drawer background transparent with no shadow, then in content set a smaller view, with a shape and shadow.
Scaffold(
topBar = { TopAppBarTablet(){
scope.launch { drawerState.open() }
} },
drawerBackgroundColor = colorResource(id = R.color.transparent),
drawerElevation = 0.dp,
drawerContent = {
Surface(
Modifier
.width(300.dp).fillMaxHeight(),
shape = RoundedCornerShape(4.dp),
color = colorResource(id = R.color.positive),
elevation = 4.dp
) {
Icon(
painter = painterResource(id = R.drawable.ic_home),
modifier = Modifier.size(25.dp),
contentDescription = null,
tint = colorResource(R.color.negative)
)
}
}
)

You can add something like this.
#Composable
fun ScaffoldWithPanel() {
Scaffold(
topBar = { ... },
bottomBar = { ... },
bodyContent = {
WithConstraints {
val parentWidth = with(AmbientDensity.current) {
constraints.maxWidth.toDp()
}
val parentHeight = with(AmbientDensity.current) {
constraints.maxHeight.toDp()
}
Box {
MainContent()
if(drawerState.value != DrawerValue.Open) {
Box(modifier = Modifier.size(parentWidth / 2, height = parentHeight)) {
SidePanel()
}
}
}
}
}
)
}
For more detail visit this website:
https://amryousef.me/side-drawer-jetpack-compose

Related

How to clip or cut a Composable?

How to clip or cut Composable content to have Image, Button or Composables to have custom shapes? This question is not about using Modifier.clip(), more like accomplishing task with alternative methods that allow outcomes that are not possible or when it's difficult to create a shape like cloud or Squircle.
This is share your knowledge, Q&A-style question which inspired by M3 BottomAppBar or BottomNavigation not having cutout shape, couldn't find question, and drawing a Squircle shape being difficult as in this question.
More and better ways of clipping or customizing shapes and Composables are more than welcome.
One of the ways for achieving cutting or clipping a Composable without the need of creating a custom Composable is using
Modifier.drawWithContent{} with a layer and a BlendMode or PorterDuff modes.
With Jetpack Compose for these modes to work you either need to set alpha less than 1f or use a Layer as in answer here.
I go with layer solution because i don't want to change content alpha
fun ContentDrawScope.drawWithLayer(block: ContentDrawScope.() -> Unit) {
with(drawContext.canvas.nativeCanvas) {
val checkPoint = saveLayer(null, null)
block()
restoreToCount(checkPoint)
}
}
block lambda is the draw scope for Modifier.drawWithContent{} to do clipping
and another extension for simplifying further
fun Modifier.drawWithLayer(block: ContentDrawScope.() -> Unit) = this.then(
Modifier.drawWithContent {
drawWithLayer {
block()
}
}
)
Clip button at the left side
First let's draw the button that is cleared a circle at left side
#Composable
private fun WhoAteMyButton() {
val circleSize = LocalDensity.current.run { 100.dp.toPx() }
Box(
modifier = Modifier
.fillMaxWidth()
.drawWithLayer {
// Destination
drawContent()
// Source
drawCircle(
center = Offset(0f, 10f),
radius = circleSize,
blendMode = BlendMode.SrcOut,
color = Color.Transparent
)
}
) {
Button(
modifier = Modifier
.padding(horizontal = 10.dp)
.fillMaxWidth(),
onClick = { /*TODO*/ }) {
Text("Hello World")
}
}
}
We simply draw a circle but because of BlendMode.SrcOut intersection of destination is removed.
Clip button and Image with custom image
For squircle button i found an image from web
And clipped button and image using this image with
#Composable
private fun ClipComposables() {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
val imageBitmap = ImageBitmap.imageResource(id = R.drawable.squircle)
Box(modifier = Modifier
.size(150.dp)
.drawWithLayer {
// Destination
drawContent()
// Source
drawImage(
image = imageBitmap,
dstSize = IntSize(width = size.width.toInt(), height = size.height.toInt()),
blendMode = BlendMode.DstIn
)
}
) {
Box(
modifier = Modifier
.size(150.dp)
.clickable { }
.background(MaterialTheme.colorScheme.inversePrimary),
contentAlignment = Alignment.Center
) {
Text(text = "Squircle", fontSize = 20.sp)
}
}
Box(modifier = Modifier
.size(150.dp)
.drawWithLayer {
// Destination
drawContent()
// Source
drawImage(
image = imageBitmap,
dstSize = IntSize(width = size.width.toInt(), height = size.height.toInt()),
blendMode = BlendMode.DstIn
)
}
) {
Image(
painterResource(id = R.drawable.squirtle),
modifier = Modifier
.size(150.dp),
contentScale = ContentScale.Crop,
contentDescription = ""
)
}
}
}
There are 2 things to note here
1- Blend mode is BlendMode.DstIn because we want texture of Destination with shape of Source
2- Drawing image inside ContentDrawScope with dstSize to match Composable size. By default it's drawn with png size posted above.
Creating a BottomNavigation with cutout shape
#Composable
private fun BottomBarWithCutOutShape() {
val density = LocalDensity.current
val shapeSize = density.run { 70.dp.toPx() }
val cutCornerShape = CutCornerShape(50)
val outline = cutCornerShape.createOutline(
Size(shapeSize, shapeSize),
LocalLayoutDirection.current,
density
)
val icons =
listOf(Icons.Filled.Home, Icons.Filled.Map, Icons.Filled.Settings, Icons.Filled.LocationOn)
Box(
modifier = Modifier.fillMaxWidth()
) {
BottomNavigation(
modifier = Modifier
.drawWithLayer {
with(drawContext.canvas.nativeCanvas) {
val checkPoint = saveLayer(null, null)
val width = size.width
val outlineWidth = outline.bounds.width
val outlineHeight = outline.bounds.height
// Destination
drawContent()
// Source
withTransform(
{
translate(
left = (width - outlineWidth) / 2,
top = -outlineHeight / 2
)
}
) {
drawOutline(
outline = outline,
color = Color.Transparent,
blendMode = BlendMode.Clear
)
}
restoreToCount(checkPoint)
}
},
backgroundColor = Color.White
) {
var selectedIndex by remember { mutableStateOf(0) }
icons.forEachIndexed { index, imageVector: ImageVector ->
if (index == 2) {
Spacer(modifier = Modifier.weight(1f))
BottomNavigationItem(
icon = { Icon(imageVector, contentDescription = null) },
label = null,
selected = selectedIndex == index,
onClick = {
selectedIndex = index
}
)
} else {
BottomNavigationItem(
icon = { Icon(imageVector, contentDescription = null) },
label = null,
selected = selectedIndex == index,
onClick = {
selectedIndex = index
}
)
}
}
}
// This is size fo BottomNavigationItem
val bottomNavigationHeight = LocalDensity.current.run { 56.dp.roundToPx() }
FloatingActionButton(
modifier = Modifier
.align(Alignment.TopCenter)
.offset {
IntOffset(0, -bottomNavigationHeight / 2)
},
shape = cutCornerShape,
onClick = {}
) {
Icon(imageVector = Icons.Default.Add, contentDescription = null)
}
}
}
This code is a bit long but we basically create a shape like we always and create an outline to clip
val cutCornerShape = CutCornerShape(50)
val outline = cutCornerShape.createOutline(
Size(shapeSize, shapeSize),
LocalLayoutDirection.current,
density
)
And before clipping we move this shape section up as half of the height to cut only with half of the outline
withTransform(
{
translate(
left = (width - outlineWidth) / 2,
top = -outlineHeight / 2
)
}
) {
drawOutline(
outline = outline,
color = Color.Transparent,
blendMode = BlendMode.Clear
)
}
Also to have a BottomNavigation such as BottomAppBar that places children on both side
i used a Spacer
icons.forEachIndexed { index, imageVector: ImageVector ->
if (index == 2) {
Spacer(modifier = Modifier.weight(1f))
BottomNavigationItem(
icon = { Icon(imageVector, contentDescription = null) },
label = null,
selected = selectedIndex == index,
onClick = {
selectedIndex = index
}
)
} else {
BottomNavigationItem(
icon = { Icon(imageVector, contentDescription = null) },
label = null,
selected = selectedIndex == index,
onClick = {
selectedIndex = index
}
)
}
}
Then we simply add a FloatingActionButton, i used offset but you can create a bigger parent and put our custom BottomNavigation and button inside it.

Android Jetpack compose: BackdropScaffold background with GoogleMap corner issue

I'm using the new BackdropScaffold composable to make a similar looking screen like Google Map with a Map on the back and a list on the front. (See the image)
As you can see there is a problem with the corner around the front layer. Currently is displayed the surface under (pale blue). What I would like to achieve is having the Google Map shown in those corners. I tried to play with the size and padding of GoogleMap composable or the front panel but no luck.
UPDATE
The following example code shows the issue I'm facing. As you can see the BackdropScaffold background is correctly applied (RED). The corners of the front layer are transparent. The issue comes out when you have a different color in your background layer (BLUE). If the background layer contains a map you have the same issue.
BackdropScaffold is dividing the space but not overlaying any layer. The front layer should overlay a bit the back layer to fix this problem.
#OptIn(ExperimentalMaterialApi::class)
#Composable
internal fun test() {
val scope = rememberCoroutineScope()
val selection = remember { mutableStateOf(1) }
val scaffoldState = rememberBackdropScaffoldState(BackdropValue.Concealed)
val frontLayerHeightDp = LocalConfiguration.current.screenHeightDp / 3
LaunchedEffect(scaffoldState) {
scaffoldState.conceal()
}
BackdropScaffold(
scaffoldState = scaffoldState,
appBar = {
TopAppBar(
title = { Text("Backdrop scaffold") },
navigationIcon = {
if (scaffoldState.isConcealed) {
IconButton(onClick = { scope.launch { scaffoldState.reveal() } }) {
Icon(Icons.Default.Menu, contentDescription = "Localized description")
}
} else {
IconButton(onClick = { scope.launch { scaffoldState.conceal() } }) {
Icon(Icons.Default.Close, contentDescription = "Localized description")
}
}
},
actions = {
var clickCount by remember { mutableStateOf(0) }
IconButton(
onClick = {
// show snackbar as a suspend function
scope.launch {
scaffoldState.snackbarHostState
.showSnackbar("Snackbar #${++clickCount}")
}
}
) {
Icon(Icons.Default.Favorite, contentDescription = "Localized description")
}
},
elevation = 0.dp,
backgroundColor = Color.Transparent
)
},
backLayerContent = {
LazyColumn(modifier = Modifier.background(Color.Blue)) {
items(if (selection.value >= 3) 3 else 5) {
ListItem(
Modifier.clickable {
selection.value = it
scope.launch { scaffoldState.conceal() }
},
text = { Text("Select $it", color = Color.White) }
)
}
}
},
backLayerBackgroundColor = Color.Red,
frontLayerShape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp),
headerHeight = frontLayerHeightDp.dp,
frontLayerBackgroundColor = Color.White,
frontLayerContent = {
LazyColumn {
items(50) {
ListItem(
text = { Text("Item $it") },
icon = {
Icon(
Icons.Default.Favorite,
contentDescription = "Localized description"
)
}
)
}
}
}
)
}
BackdropScaffold is creating a Surface for from layer under the hood, when you create your own inside frontLayerContent it's displayed on top of built-in one.
Instead use frontLayerShape and frontLayerBackgroundColor parameters:
frontLayerShape = BottomSheetShape,
frontLayerBackgroundColor = Color.White,
frontLayerContent = {
LazyColumn(
modifier = Modifier.padding(16.dp)
) {
items(
items = moorings,
itemContent = { mooring ->
...
}
)
}
}
p.s. some comments about your code:
When you have modifier parameter, you should only apply it for the topmost container in your view - here you've applied it for content of frontLayerContent, which may cause unexpected behaviour.
You don't need to wrap LazyColumn in a Column - it has no effect when Column has only one child, and if you need to apply a modifier you can do it directly for LazyColumn

Floating Button goes up with Bottom Sheet Jetpack Compose

I don't understand why the FloatingButton is going up with the BottomSheet.
I tried to change the sheetElevation which is higher than the elevation of the FloatingButton, but the issue remains. That's because the code inside BottomSheetScaffoldStack says to move the FloatingButton up along with the BottomSheet. Is there any way to avoid that?
Here is the code of the BottomSheetScaffold:
BottomSheetScaffold(
scaffoldState = bottomSheetScaffoldState,
topBar = { TopBar(
areButtonShowed = true,
title = topBarTitle,
onBackPressed = { BendRouter.navigateTo(onBackDestination) }
) },
floatingActionButtonPosition = FabPosition.Center,
floatingActionButton = {
ExtendedFloatingButton(
text = context.getString(R.string.start),
onClick = {}, // TODO
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.padding(
start = 24.dp,
end = 24.dp
),
backgroundColor = PureWhite
)
Spacer(modifier = Modifier.height(150.dp))
},
sheetBackgroundColor = PureWhite,
sheetPeekHeight = 0.dp,
sheetElevation = 70.dp,
sheetShape = RoundedCornerShape(50.dp),
sheetContent = {
openStretchDetails?.let { stretch ->
BottomSheetView(stretch = stretch)
}
},
content = { RoutinePageView(viewModel) }
)
And ExtendedFloatingButton:
#Composable
fun ExtendedFloatingButton(
text: String,
#DrawableRes icon: Int? = null,
onClick: () -> Unit,
modifier: Modifier = Modifier,
elevation: Dp = 12.dp,
backgroundColor: Color
) {
ExtendedFloatingActionButton(
text = {
Text(
text = text.uppercase(),
color = Gray,
fontSize = 18.sp,
maxLines = 1,
fontWeight = FontWeight.Bold,
letterSpacing = .5.sp
)
},
onClick = onClick,
icon = {
icon?.let {
Icon(
painter = painterResource(id = it),
contentDescription = ""
)
}
},
modifier = modifier,
elevation = FloatingActionButtonDefaults.elevation(elevation),
backgroundColor = backgroundColor
)
}
The BottomSheetScaffold has a default behavior that you can see by clicking on it while pressing CTRL. Looking at BottomSheetScaffoldStack inside the BottomSheetScaffold.kt class you'll see how the FloatingButton is moved along with the BottomSheet.
To solve this problem I used ModalBottomSheetLayout instead of BottomSheetScaffold.
ModalBottomSheetLayout(
sheetState = bottomState,
sheetContent = {
Box(Modifier.defaultMinSize(minHeight = 1.dp)) {
openStretchDetails?.let { stretch ->
BottomSheetView(stretch = stretch)
coroutineScope.launch {
bottomState.animateTo(ModalBottomSheetValue.Expanded)
}
}
}
},
sheetBackgroundColor = PureWhite,
sheetElevation = 16.dp,
sheetShape = RoundedCornerShape(50.dp),
) {
Scaffold(
topBar = { TopBar(
areButtonShowed = true,
title = topBarTitle,
onBackPressed = { BendRouter.navigateTo(onBackDestination) }
) },
floatingActionButtonPosition = FabPosition.Center,
floatingActionButton = {
ExtendedFloatingButton(
text = context.getString(R.string.start),
onClick = {}, // TODO
modifier = Modifier
.fillMaxWidth()
.height(45.dp)
.padding(
start = 24.dp,
end = 24.dp
),
backgroundColor = PureWhite
)
Spacer(modifier = Modifier.height(150.dp))
},
content = { RoutinePageView(viewModel) }
)
}
Add this on the top:
val bottomState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
confirmStateChange = { it != ModalBottomSheetValue.HalfExpanded }
)
val coroutineScope = rememberCoroutineScope()

How to reduce horizontal space between navigation icon and title in a jetpack compose `TopAppBar`?

I'm making an app bar in jetpack compose but I'm having spacing issues between the navigation icon and the title.
This is my compose function:
#Composable
fun DetailsAppBar(coin: Coin, backAction: () -> Unit) {
TopAppBar(
navigationIcon = {
IconButton(onClick = { backAction() }) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = null
)
}
},
title = { Text(text = "${coin.rank}. ${coin.name} (${coin.symbol})") }
)
}
This is my preview function:
#Composable
#Preview
fun DetailsAppBarPreview() {
val bitcoin = Coin(
id = "",
isActive = true,
name = "Bitcoin",
rank = 1,
symbol = "BTC"
)
DetailsAppBar(coin = bitcoin, backAction = {})
}
This is the visual preview of my compose function:
This is the space I want to reduce:
Entering the code of the TopAppBar compose function I can't see any parameters that allow me to do this.
You are right. With the variant of TopAppBar you are using, this is not possible. This is because the width of the NavigationIcon is set to the default (72.dp - 4.dp). You can check the implementation of TopAppBar and see that it uses the below:
private val AppBarHorizontalPadding = 4.dp
// Start inset for the title when there is a navigation icon provided
private val TitleIconModifier = Modifier.fillMaxHeight()
.width(72.dp - AppBarHorizontalPadding)
What you could do is to use the other variant of the TopAppBar that gives you much more control in placing the title and icon. It could be something like:
#Composable
fun Toolbar(
#StringRes title: Int,
onNavigationUp: (() -> Unit)? = null,
) {
TopAppBar(backgroundColor = MaterialTheme.colors.primary) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(56.dp)
) {
// Title
Text(...)
// Navigation Icon
if (onNavigationUp != null) {
Icon(
painter = painterResource(id = R.drawable.ic_back),
contentDescription = stringResource(
id = R.string.back
),
tint = MaterialTheme.colors.onPrimary,
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable { onNavigationUp() }
.padding(16.dp)
...... ,
)
}
}
}
}
Actually it is possible to reduce space between icon and and title but it's a little bit tricky. Just add negative offset to modifier of text like that
#Composable
fun DetailsAppBar(coin: Coin, backAction: () -> Unit) {
TopAppBar(
navigationIcon = {
IconButton(onClick = { backAction() }) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = null
)
}
},
title = {
Text(
text = "${coin.rank}. ${coin.name} (${coin.symbol})",
modifier = Modifier.offset(x = (-16).dp)
)
}
)
}

fitsSystemWindows counterpart in jetpack compose

I have a transparent status/navigation bars, and when I place a compose element with default layout(top/left), it's placed under the status bar. In xml I use fitsSystemWindows to fix this, how can I get same effect in jetpack compose?
This works for me, In Activity I have :
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
JetpackComposePlaygroundTheme {
val controller = rememberAndroidSystemUiController()
CompositionLocalProvider(LocalSystemUiController provides controller) {
ProvideWindowInsets {
ComposeAppPlayground()
}
}
}
}
Then In compose app playground I have something like this:
Surface {
var topAppBarSize by remember { mutableStateOf(0) }
val contentPaddings = LocalWindowInsets.current.systemBars.toPaddingValues(
top = false,
additionalTop = with(LocalDensity.current) { topAppBarSize.toDp() }
)
Column(modifier = Modifier.navigationBarsPadding().padding(top = contentPaddings.calculateTopPadding())) {
// content can go here forexample...
// if you want the content go below status bar
// you can remove the top padding for column
}
InsetAwareTopAppBar(
title = { Text(stringResource(R.string.home)) },
backgroundColor = MaterialTheme.colors.surface.copy(alpha = 0.9f),
modifier = Modifier
.fillMaxWidth()
.onSizeChanged { topAppBarSize = it.height }
)
}
}
Also the InsetAwareTopAppBar I found from guids mentioned in https://google.github.io/accompanist/insets/
#Composable
fun InsetAwareTopAppBar(
title: #Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: #Composable (() -> Unit)? = null,
actions: #Composable RowScope.() -> Unit = {},
backgroundColor: Color = MaterialTheme.colors.primarySurface,
contentColor: Color = contentColorFor(backgroundColor),
elevation: Dp = 4.dp
) {
Surface(
color = backgroundColor,
elevation = elevation,
modifier = modifier
) {
TopAppBar(
title = title,
navigationIcon = navigationIcon,
actions = actions,
backgroundColor = Color.Transparent,
contentColor = contentColor,
elevation = 0.dp,
modifier = Modifier
.statusBarsPadding()
.navigationBarsPadding(bottom = false)
)
}
}

Categories

Resources