TopAppBar and padding (Jetpack Compose) - android

I have a slightly different expectation for padding to work. How can this problem be solved? I see this only at TopAppBar.
CenterAlignedTopAppBar(
title = { Text(title) },
modifier = Modifier.statusBarsPadding(), // or padding(top = 24.dp)
actions = {
if (isSync) {
IconButton(
onClick = { },
enabled = false,
content = {
Icon(
painter = painterResource(R.drawable.ic_outline_cloud_download_24),
contentDescription = title,
tint = Color.DarkGray.copy(alpha = alpha)
)
}
)
}
},
scrollBehavior = scrollBehavior
)
UPD
For example, here it works as it should -> link

I made it myself based on the source code. Not quite universal, but just right for me. I will not give the full code, it is in the source code. I will give only the place where it is necessary to add.
#Composable
private fun TopAppBarLayout(...) {
Layout(
...,
modifier = modifier.statusBarsPadding()
) {
...
}
}
The rest of the code is identical to the original.
UPDATE 21
Now everything works out of the box.

Related

Why can't I use Modifier.padding(top = 20.dp) to increase space in AlertDialog when I use JetPack Compose?

The Code A displays a dialog box based AlertDialog, and I get Image A when I run Code A.
I find the space between title = { Text(text = dialogTitle) } and text = {...} is too closer in Image A.
So I set Modifier.padding(top = 100.dp) to wish to increase the space between the two controls, but I only get Image B, it seems that Modifier.padding(top = 100.dp) doesn't work as expected, how can I fix it?
Code A
#Composable
fun EditTextDialog(
isShow: Boolean,
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
saveTitle: String = stringResource(R.string.dialog_save_title),
cancelTitle:String = stringResource(R.string.dialog_cancel_title),
dialogTitle:String ="Edit",
editFieldContent:String ="",
) {
var mText by remember(editFieldContent){ mutableStateOf(editFieldContent) }
val cleanAndDismiss = {
mText = editFieldContent
onDismiss()
}
if (isShow) {
AlertDialog(
title = { Text(text = dialogTitle) },
text = {
Column(
Modifier.padding(top = 20.dp)
//Modifier.padding(top = 100.dp)
//Modifier.height(100.dp), //The same result as Image A
//verticalArrangement = Arrangement.Center
) {
TextField(
value = mText,
onValueChange = { mText = it }
)
}
},
confirmButton = {
TextButton(onClick = { onConfirm(mText) }) {
Text(text = saveTitle)
}
},
dismissButton = {
TextButton(onClick = cleanAndDismiss) {
Text(text = cancelTitle)
}
},
onDismissRequest = cleanAndDismiss
)
}
}
Image A
Image B
With M3 AlertDialog (androidx.compose.material3.AlertDialog) it works.
With M2 AlertDialog, one solution is to remove the title attribute and use the text attribute for the whole layout.
AlertDialog(
onDismissRequest = {},
text = {
Column(){
Text(text = "Title")
Spacer(Modifier.height(30.dp))
TextField(
value = "mText",
onValueChange = { },
)
}
},
//buttons..
)
I don't understand what you're trying to do. If you want more space between the TextField and the dialog buttons, then you don't want a top padding. You want padding below the TextField, so it would be bottom padding on the column.
Also, there's a chance that it won't work properly inside a Column, and you might have to switch it out for Box. And if that doesn't work for some reason, just add a spacer below the TextField:
Spacer(Modifier.height(20.dp).fillMaxWidth())
I assume you are using Material AlertDialog? If yes try using the Material3 variant. It should work then.
Just implement following library:
implementation "androidx.compose.material3:material3:1.0.0-beta02"
And make sure to use the Material3 AlertDialog Composable which is imported with the library.

Jetpack Compose LargeTopAppBar Displays Title Twice

I'm trying to build a Jetpack Compose app with Scaffold and a LargeTopAppBar. I currently have a very simple UI with only the LargeTopAppBar in a Scaffold, but when I run my app I see two small titles at the top of the screen.
Any ideas why this is happening or how to fix it? My activity code is as follows
#OptIn(ExperimentalMaterial3Api::class)
class MainActivity : MonetCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launchWhenCreated {
monet.awaitMonetReady()
setContent {
TVTimeTheme(monetCompat = monet) {
val decayAnimationSpec = rememberSplineBasedDecay<Float>()
val topAppBarScrollState = rememberTopAppBarScrollState()
val scrollBehavior = remember(decayAnimationSpec) {
TopAppBarDefaults.exitUntilCollapsedScrollBehavior(
decayAnimationSpec, topAppBarScrollState
)
}
Scaffold (
topBar = {
LargeTopAppBar(
title = { Text(text = "movies") },
scrollBehavior = scrollBehavior
)
}
) { innerPadding ->
Box(modifier = Modifier.padding(innerPadding))
}
}
}
}
}
}
These helped me:
Use only material3 components (androidx.compose.material3.*) in TabBar, not material (androidx.compose.material.*) components
Remove defaultTextColor of titleLarge and bodyLarge in your typography
I ran across this issue when I set the color within the Text composable, instead of the titleContentColor associated with the TopAppBar composable.
I was doing this:
MediumTopAppBar(
title = {
Text(
text = "Example",
color = MaterialTheme.colorScheme.secondary
)
},
...
)
Instead, use the titleContentColor field on the MediumTopAppBar composable itself. That looks like this:
MediumTopAppBar(
title = {
Text(
text = "Example",
)
},
colors = TopAppBarDefaults.largeTopAppBarColors(
titleContentColor = MaterialTheme.colorScheme.secondary
)
)
Easy mistake to make but stumped me for a good 10 minutes or so!
I think it's because you have not put your navigation icon yet. Try this:
Scaffold(
topBar = {
LargeTopAppBar(
title = { Text("movies") },
navigationIcon = {
IconButton(onClick = { }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "menu icon"
)
}
},
actions = {
IconButton(onClick = { }) {
Icon(
imageVector = Icons.Filled.Favorite,
contentDescription = "favorite icon"
)
}
},
)
},
content = {innerPadding ->
Box(modifier = Modifier.padding(innerPadding))
}
)
Source
Just make sure that whether you use import androidx.compose.material3.Text instead of import androidx.compose.material.Text

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

Increase space between title and text of AlertDialog in Compose

In a simple AlertDialog like the following
AlertDialog(
modifier = Modifier,
title = {
Text(text = "Title")
},
text = {
Column(
modifier = Modifier.fillMaxWidth()
) {
TextButton() {
Text("Text 1")
}
TextButton() {
Text("Text 2")
}
}
},
confirmButton = {},
dismissButton = {}
)
how can I set a spacing between title and the first TextButton?
I tried to set a .padding(top = X.dp) to the Column, or the first text button, but this seems to only create a space at the bottom of the AlertDialog.
Also setting a custom .height(X.dp) did not work.
I'm using Compose 1.0.3
As #Abhimanyu perfectly explains why it's not working right now, here's the workaround I'm using to achieve the desired padding: putting the title in the content. AlertDialog's title param is optional, so it can be omitted/set to null, and instead the actual title can be put in the text parameter (which holds the dialog content).
#Composable
fun MyComposable() {
AlertDialog(
title = null,
text = {
Column {
Text(
modifier = Modifier.padding(vertical = 16.dp),
text = "Actual title"
)
// Rest of the dialog content
}
}
)
}
This is NOT an answer. It only provides info on why this is not possible.
The requirement seems not achievable at this point (6th Oct 2021) with the current compose version (1.0.3).
Will update this once that is possible.
The AlertDialog code does not respect the padding values provided.
AlertDialog.kt
// Baseline distance from the first line of the text to the last line of the title
private val TextBaselineDistanceFromTitle = 36.sp
The text offset used for the positioning is calculated like this.
val textOffset = if (titlePlaceable == null) {
TextBaselineDistanceFromTop.roundToPx()
} else {
TextBaselineDistanceFromTitle.roundToPx()
}
The distance between the first text in the text composable and the last text in the title composable is always 36.sp.
The Alert Dialog code in compose seems too hackish currently and I could see a few TODO's in the code.
Hopefully, the code will be changed to handle more scenarios soon.
I'm using this composable as first child inside Column
#Composable
fun HackySpacer(space: Dp) {
Box(
modifier = Modifier
.height(space)
.fillMaxWidth()
) {
Text(text = "")
}
}
It's not perfect, but it works for my usecase.
Is now possible using the new AlertDialog from Compose Material 3.
The default spacing between title and text is much more reasonable and it is also possible to add Modifier.padding() or Spacer() to both.
implementation("androidx.compose.material3:material3:1.0.0-alpha01")
androidx.compose.material3.AlertDialog(
onDismissRequest = {
openDialog.value = false
},
title = {
Text(text = "Title", modifier = Modifier.padding(50.dp))
},
text = {
Spacer(Modifier.height(50.dp))
Text(text = "Turned on by default")
},
confirmButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text("Confirm")
}
},
dismissButton = {
TextButton(
onClick = {
openDialog.value = false
}
) {
Text("Dismiss")
}
}
)

Dynamic row width compose

I need to create a searchbar that looks like this (strictly compose):
Now i managed to get the one without text working, but i cannot get the cancel text to show up without bugs.
For example when using constraint row and some paddings i get effect like this
link to the working code:
https://gist.github.com/piotrsedlak/d71da26299946ef6fc5125042e04a154
I also tried working with animateContentSize but that didnt really help.
I think this can be easily achieved using weight modifier. Conditionally adjust the weights and you'll get the desired effect. Here's a snippet for the same:
#Composable
fun DynamicToolbar() {
var text by remember { mutableStateOf(TextFieldValue()) }
val fieldWeight = if (text.text.isNotBlank()) 0.8f else 1f
Row(modifier = Modifier.fillMaxWidth()
) {
OutlinedTextField(
value = text,
onValueChange = { text = it },
leadingIcon = { Icon(Icons.Default.Search, null, tint = Color.DarkGray) },
trailingIcon = {
if (text.text.isNotBlank()) {
Icon(
Icons.Default.Close,
null,
tint = Color.LightGray,
modifier = Modifier.clickable { text = text.copy("") }
)
}
},
modifier = Modifier
.weight(fieldWeight)
.alignBy(FirstBaseline)
)
if (text.text.isNotBlank()) {
TextButton(
onClick = { },
modifier = Modifier
.fillMaxWidth()
.weight(1 - fieldWeight)
.alignBy(FirstBaseline)
) {
Text("Cancel")
}
}
}
}
I'm using Compose 1.0.0-alpha11
PS: I fixed the baseline alignment problem as well (credits). Hope that helps.

Categories

Resources