fitsSystemWindows counterpart in jetpack compose - android

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

Related

Jetpack Compose: How to create multi-item FAB with animation?

I'm trying to create a multi-item floating action button with the following animation:
I created a multi-item floating action button but I could not implement the intended animation.
I have FilterFabMenuButton composable that I show as a menu item :
FilterFabMenuButton
#Composable
fun FilterFabMenuButton(
item: FilterFabMenuItem,
onClick: (FilterFabMenuItem) -> Unit,
modifier: Modifier = Modifier
) {
FloatingActionButton(
modifier = modifier,
onClick = {
onClick(item)
},
backgroundColor = colorResource(
id = R.color.primary_color
)
) {
Icon(
painter = painterResource(item.icon), contentDescription = null, tint = colorResource(
id = R.color.white
)
)
}
}
I have FilterFabMenuLabel composable which is a label for FilterFabMenuButton:
FilterFabMenuLabel
#Composable
fun FilterFabMenuLabel(
label: String,
modifier: Modifier = Modifier
) {
Surface(
modifier = modifier,
shape = RoundedCornerShape(6.dp),
color = Color.Black.copy(alpha = 0.8f)
) {
Text(
text = label, color = Color.White,
modifier = Modifier.padding(horizontal = 20.dp, vertical = 2.dp),
fontSize = 14.sp,
maxLines = 1
)
}
}
I have FilterFabMenuItem composable which is a Row that contains FilterFabMenuLabel and FilterFabMenuButton composables:
FilterFabMenuItem
#Composable
fun FilterFabMenuItem(
menuItem: FilterFabMenuItem,
onMenuItemClick: (FilterFabMenuItem) -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
//label
FilterFabMenuLabel(label = menuItem.label)
//fab
FilterFabMenuButton(item = menuItem, onClick = onMenuItemClick)
}
}
I have FilterFabMenu composable which is a Column that shows menu items:
FilterFabMenu
#Composable
fun FilterFabMenu(
visible: Boolean,
items: List<FilterFabMenuItem>,
modifier: Modifier = Modifier
) {
val enterTransition = remember {
expandVertically(
expandFrom = Alignment.Bottom,
animationSpec = tween(150, easing = FastOutSlowInEasing)
) + fadeIn(
initialAlpha = 0.3f,
animationSpec = tween(150, easing = FastOutSlowInEasing)
)
}
val exitTransition = remember {
shrinkVertically(
shrinkTowards = Alignment.Bottom,
animationSpec = tween(150, easing = FastOutSlowInEasing)
) + fadeOut(
animationSpec = tween(150, easing = FastOutSlowInEasing)
)
}
AnimatedVisibility(visible = visible, enter = enterTransition, exit = exitTransition) {
Column(
modifier = modifier.fillMaxWidth(), horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
items.forEach { menuItem ->
FilterFabMenuItem(
menuItem = menuItem,
onMenuItemClick = {}
)
}
}
}
}
I have FilterFab composable that expands/collapses FilterMenu:
FilterFab
#Composable
fun FilterFab(
state: FilterFabState,
rotation:Float,
onClick: (FilterFabState) -> Unit,
modifier: Modifier = Modifier
) {
FloatingActionButton(
modifier = modifier
.rotate(rotation),
elevation = FloatingActionButtonDefaults.elevation(defaultElevation = 0.dp),
onClick = {
onClick(
if (state == FilterFabState.EXPANDED) {
FilterFabState.COLLAPSED
} else {
FilterFabState.EXPANDED
}
)
},
backgroundColor = colorResource(
R.color.primary_color
),
shape = CircleShape
) {
Icon(
painter = painterResource(R.drawable.fab_add),
contentDescription = null,
tint = Color.White
)
}
}
Last but not least, I have a FilterView composable which is a Column that contains FilterFabMenu and FilterFab composables:
FilterView
#SuppressLint("UnusedTransitionTargetStateParameter")
#Composable
fun FilterView(
items: List<FilterFabMenuItem>,
modifier: Modifier = Modifier
) {
var filterFabState by rememberSaveable() {
mutableStateOf(FilterFabState.COLLAPSED)
}
val transitionState = remember {
MutableTransitionState(filterFabState).apply {
targetState = FilterFabState.COLLAPSED
}
}
val transition = updateTransition(targetState = transitionState, label = "transition")
val iconRotationDegree by transition.animateFloat({
tween(durationMillis = 150, easing = FastOutSlowInEasing)
}, label = "rotation") {
if (filterFabState == FilterFabState.EXPANDED) 230f else 0f
}
Column(
modifier = modifier.fillMaxSize().padding(16.dp), horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.spacedBy(16.dp,Alignment.Bottom)
) {
FilterFabMenu(items = items, visible = filterFabState == FilterFabState.EXPANDED)
FilterFab(
state = filterFabState,
rotation = iconRotationDegree, onClick = { state ->
filterFabState = state
})
}
}
This produces the following result:
expandVertically in your enterTransition is not the correct approach for this kind of animation. Per documentation, it animates a clip revealing the content of the animated item from top to bottom, or vice versa. You apply this animation to the entire column (so all items at once), resulting in the gif you have shown us.
Instead, you should use a different enter/exit animation type, maybe a custom animation where you work with the item scaling to emulate the "pop in" effect like such:
scaleFactor.animateTo(2f, tween(easing = FastOutSlowInEasing, durationMillis = 50))
scaleFactor.animateTo(1f, tween(easing = FastOutSlowInEasing, durationMillis = 70))
(the scaleFactor is an animatabale of type Animatable<Float, AnimationVector1D> in this instance).
Then you create such an animatable for each of the column items, i.e. your menu items. After that, just run the animations in a for loop for each menu item inside a coroutine scope (since compose animations are suspend by default, they will run in sequence, use async/awaitAll if you want to do it in parallel).
Also, don't forget to put your animatabales in remember {}, then just use the values you are animating like scaleFactor inside modifiers of your column items, and trigger them inside a LaunchedEffect when you click to expand/close the menu.

Jetpack Compose TopAppBar wrong color

I'm trying to have a white top app bar using Jetpack Compose but the color is grey instead of white.
Here is my code:
#Composable
fun AppTheme(content: #Composable () -> Unit) {
MaterialTheme(
colors = Colors(
primary = colorResource(R.color.colorPrimary),
primaryVariant = colorResource(R.color.colorPrimaryVariant),
secondary = colorResource(R.color.colorSecondary),
secondaryVariant = colorResource(R.color.colorSecondaryVariant),
background = colorResource(R.color.white),
surface = colorResource(R.color.white),
error = colorResource(R.color.failure),
onPrimary = colorResource(R.color.colorOnPrimary),
onSecondary = colorResource(R.color.colorOnSecondary),
onBackground = colorResource(R.color.colorOnBackground),
onSurface = colorResource(R.color.colorOnSurface),
onError = colorResource(R.color.white),
isLight = false
),
typography = Typography(),
shapes = Shapes(),
content = content
)
}
#Composable
#Preview
fun TestTopBar() {
AppTheme {
TopBar(title = R.string.common_country, actions = actions())
}
}
#Composable
fun actions(): #Composable RowScope.() -> Unit = {
IconButton(onClick = {}) { Icon(Icons.Filled.Search, "Search") }
}
#Composable
fun TopBar(title: Int, actions: #Composable (RowScope.() -> Unit) = {}) {
TopAppBar(backgroundColor = Color.White) {
//CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) {
Box {
// navigation icon
Row(Modifier.align(Alignment.CenterStart), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = { }) {
Icon(Icons.Filled.ArrowBack, "Back")
}
}
// title
Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) {
Text(
modifier = Modifier
.fillMaxWidth()
.alpha(1f),
textAlign = TextAlign.Center,
maxLines = 1,
text = stringResource(title),
style = MaterialTheme.typography.h6
)
}
// actions
Row(
Modifier.align(Alignment.CenterEnd),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically,
content = actions
)
}
//}
}
}
I've set the surface as white in my theme. I've also set the background color of the top app bar as white. Still, the preview display a light grey instead of white.

How to remove padding between AlertDialog and title/text with Compose

Using compose, I want to create something like this :
Problem is using compose AlertDialog I only achieve to get this :
There is a padding between the AlertDialog border and the title that can not be removed. How to remove it using Compose ?
Using Modifier.padding(all = 0.dp) doesn't work. I tried it at every level.
Properties "title" and "text" are wrapped with AlertDialogBaselineLayout that is adding padding. You can't remove it.
I have made a custom Composable that is acting as an AlertDialog and doesn't use AlertDialogBaselineLayout.
You can copy/paste it and edit it according to your needs :
NoPaddingAlertDialog :
#Composable
fun NoPaddingAlertDialog(
onDismissRequest: () -> Unit,
modifier: Modifier = Modifier,
title: #Composable (() -> Unit)? = null,
text: #Composable (() -> Unit)? = null,
confirmButton: #Composable () -> Unit,
dismissButton: #Composable (() -> Unit)? = null,
shape: Shape = MaterialTheme.shapes.medium,
backgroundColor: Color = MaterialTheme.colors.surface,
contentColor: Color = contentColorFor(backgroundColor),
properties: DialogProperties = DialogProperties()
) {
Dialog(
onDismissRequest = onDismissRequest,
properties = properties
) {
Surface(
modifier = modifier,
shape = shape,
color = backgroundColor,
contentColor = contentColor
) {
Column(
modifier = Modifier
.fillMaxWidth()
) {
title?.let {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) {
val textStyle = MaterialTheme.typography.subtitle1
ProvideTextStyle(textStyle, it)
}
}
text?.let {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) {
val textStyle = MaterialTheme.typography.subtitle1
ProvideTextStyle(textStyle, it)
}
}
Box(
Modifier
.fillMaxWidth()
.padding(all = 8.dp)
) {
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier.fillMaxWidth()
) {
dismissButton?.invoke()
confirmButton()
}
}
}
}
}
}
You can then easily use it this way :
#Composable
fun MyCustomAlertDialog(openDialog: MutableState<Boolean> = mutableStateOf(true)) {
if (openDialog.value) {
NoPaddingAlertDialog(
title = {
Surface(
color = Color.Blue,
contentColor = Color.White,
modifier = Modifier
.fillMaxWidth()
) {
Text(
text = " Popup Title️",
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 16.dp),
)
}
},
text = {
Column(Modifier.fillMaxWidth()) {
OutlinedTextField(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(horizontal = 8.dp, vertical = 16.dp)
.fillMaxWidth(),
value = "Alert Dialog content ...",
onValueChange = { },
label = { Text(text = "Content") },
)
}
},
onDismissRequest = { /*TODO*/ },
confirmButton = {
PopupButton(title = "Ok", setShow = {
openDialog.value = false
})
},
dismissButton = {
PopupButton(
title = "Cancel",
setShow = {
openDialog.value = false
}
)
}
)
}
}
And get this :
You can use a Dialog() instead of AlertDialog(). It allows you to pass in a composable as the content parameter, so you can set whatever padding you want. Just don't forget to set the background color in the root composable of the content, since it is transparent by default.

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

Jetpack Compose onClick ripple is not propagating with a circular motion?

As can be seen in gif
when Column that contains of Text, Spacer, and LazyRowForIndexed is touched ripple is not propagating with circular motion. And it gets touched effect even when horizontal list is touched.
#Composable
fun Chip(modifier: Modifier = Modifier, text: String) {
Card(
modifier = modifier,
border = BorderStroke(color = Color.Black, width = Dp.Hairline),
shape = RoundedCornerShape(8.dp)
) {
Row(
modifier = Modifier.padding(start = 8.dp, top = 4.dp, end = 8.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier.preferredSize(16.dp, 16.dp)
.background(color = MaterialTheme.colors.secondary)
)
Spacer(Modifier.preferredWidth(4.dp))
Text(text = text)
}
}
}
#Composable
fun TutorialSectionCard(model: TutorialSectionModel) {
Column(
modifier = Modifier
.padding(top = 8.dp)
.clickable(onClick = { /* Ignoring onClick */ })
.padding(16.dp)
) {
Text(text = model.title, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.h6)
Spacer(Modifier.preferredHeight(8.dp))
Providers(AmbientContentAlpha provides ContentAlpha.medium) {
Text(model.description, style = MaterialTheme.typography.body2)
}
Spacer(Modifier.preferredHeight(16.dp))
LazyRowForIndexed(items = model.tags) { _: Int, item: String ->
Chip(text = item)
Spacer(Modifier.preferredWidth(4.dp))
}
}
}
#Preview
#Composable
fun TutorialSectionCardPreview() {
val model = TutorialSectionModel(
clazz = MainActivity::class.java,
title = "1-1 Column/Row Basics",
description = "Create Rows and Columns that adds elements in vertical order",
tags = listOf("Jetpack", "Compose", "Rows", "Columns", "Layouts", "Text", "Modifier")
)
Column {
TutorialSectionCard(model)
TutorialSectionCard(model)
TutorialSectionCard(model)
}
}
What should be done to have circular effect, but not when list itself or an item from list is touched, or scrolled?
You have to apply a Theme to your composable, which in turn provides a default ripple factory, or you have to set the ripple explicitly:
#Preview
#Composable
fun TutorialSectionCardPreview() {
MaterialTheme() {
Column {
TutorialSectionCard
...
}
}
}
or
Column(
modifier = Modifier
.padding(top = 8.dp)
.clickable(
onClick = { /* Ignoring onClick */ },
indication = rememberRipple(bounded = true)
)
.padding(16.dp)
) {
// content
}
(As of compose version 1.0.0-alpha09 there seems to be no way to prevent the ripple from showing when content is scrolled)
I'm using this approach:
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(
color = Color.Black
),
onClick = {
}
)
I also figured out how to keep ripple only for the card not the scrollable list that contains tags. To prevent ripple only move through cards use a Box which places it's children as a stack, and add clickable to section that contains header and text.
#Composable
fun TutorialSectionCard(
model: TutorialSectionModel,
onClick: ((TutorialSectionModel) -> Unit)? = null
) {
Card(
modifier = Modifier.padding(vertical = 3.dp, horizontal = 8.dp),
elevation = 1.dp,
shape = RoundedCornerShape(8.dp)
) {
Box(
contentAlignment = Alignment.BottomStart
) {
TutorialContentComponent(onClick, model)
TutorialTagsComponent(model)
}
}
}
#Composable
private fun TutorialContentComponent(
onClick: ((TutorialSectionModel) -> Unit)?,
model: TutorialSectionModel
) {
Column(Modifier
.clickable(
onClick = { onClick?.invoke(model) }
)
.padding(16.dp)
) {
Text(
text = model.title,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.h6
)
// Vertical spacing
Spacer(Modifier.height(8.dp))
// Description text
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(model.description, style = MaterialTheme.typography.body2)
}
// Vertical spacing
Spacer(Modifier.height(36.dp))
}
}
#Composable
private fun TutorialTagsComponent(model: TutorialSectionModel) {
Column(Modifier.padding(12.dp)) {
// Horizontal list for tags
LazyRow(content = {
items(model.tags) { tag ->
TutorialChip(text = tag)
Spacer(Modifier.width(8.dp))
}
})
}
}

Categories

Resources