Snackbar text parameter deprecated - android

So i am working with an app in jetpack compose and i see this tutorial Tutorial. This tutorial builds a default snackbar within a snackbarhost and adds a text to this snackbar in the way below. Though when i try to add this parameter it tells me that it doesn't exist. Why is this is the parameter deprecated and if so what did it get exchanged with? Plus i have the question of how to clear the que in the snackbarhost quz when i click more then once i first get myh last message and then the one i should get?
Snackbar(
modifier = Modifier.padding(16.dp),
text = {
Text(
text = data.message,
style = MaterialTheme.typography.body2,
color = Color.White
)
},
action = {
data.actionLabel?.let { actionLabel ->
TextButton(
onClick = {
onDismiss()
}
) {
Text(
text = actionLabel,
style = MaterialTheme.typography.body2,
color = Color.White
)
}
}
}
)

I'm assume your talking about this line:
Snackbar(
modifier = Modifier.padding(16.dp),
text = { // <--
I found a usage example on the Compose Playground here: https://foso.github.io/Jetpack-Compose-Playground/material/snackbar/ (the page also contains a link to the reference of Snackbar)
From what I can see, they probably replaced the text arg with the content of the Snackbar, which would result in something similar to this:
Snackbar(
modifier = ... same as before ...,
action = ... same as before ...
) {
// Move the text element here
Text(...)
}

Related

How to add subtitle to the LargeTopAppBar in jetpack compose?

I have a problem with adding subtitle to the TopAppBar Composable. I am trying to implement LargeTopAppBar from Material Design 3, but with extra subtitle on it. The issue I am currently facing is that it renders twice. Below is my Composable:
#Composable
private fun HomeTopBar(
modifier: Modifier = Modifier,
title: String,
subtitle: String,
navigateToProfileScreen: () -> Unit,
navigateToAboutScreen: () -> Unit
) {
LargeTopAppBar(
modifier = modifier,
title = {
Column {
Text(
text = title,
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onSurface
)
Text(
text = subtitle,
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
},
actions = {
NavigationDropDownMenu(
navigateToProfileScreen = navigateToProfileScreen,
navigateToAboutScreen = navigateToAboutScreen
)
},
)
}
For some reason it renders twice. I think that this problem is related to the fact that this top app bar has 2 modes (pinned and expanded).
Visual preview:
Here is preview of my composable function to highlight the problem:
Dependencies I used in the project:
implementation 'androidx.compose.material3:material3:1.0.0-beta01'
compose_version = '1.3.0-beta01'
You have to remove the color attribute inside the Text elements in the title and subtitle.
Text(
text = title,
style = MaterialTheme.typography.headlineMedium,
//color = MaterialTheme.colorScheme.onSurface
)
Currently you can only define the same color for both Text using the colors attribute in the LargeTopAppBar :
LargeTopAppBar(
colors = TopAppBarDefaults.largeTopAppBarColors(
titleContentColor=MaterialTheme.colorScheme.onSurface
),
//...
)
Finally use only M3 components (androidx.compose.material3.*) in the LargeTopAppBar, not M2 (androidx.compose.material.*) components.
.

Jetpack Compose, how to change the color of the action of the snackbar in .showSnackbar() in a Scaffold?

So, I'm showing a snackbar inside of my Scaffold, using the scaffoldState.snackbarHostState.showSnackbar() method, though the colour of the "Undo" action is dark purple, and I would like to change it to something else.
I know that I can show it as a custom component, though I would like to launch it in a coroutineScope(), which I think is not possible.
My code is like this for the snackbar.
scope.launch {
val result = scaffoldState.snackbarHostState.showSnackbar(
message = "Note Deleted",
actionLabel = "Undo",
)
if (result == SnackbarResult.ActionPerformed) {
viewModel.onEvent(NotesEvent.RestoreNote)
}
}
I would like to know if it's possible to change the text colour of the action here and if yes, it would be cool if you could give an example or a resource.
Thanks!
You can customize your Snackbar using the actionColor parameter.
Something like:
val scaffoldState = rememberScaffoldState()
Scaffold(
scaffoldState = scaffoldState,
snackbarHost = {
// reuse default SnackbarHost to have default animation and timing handling
SnackbarHost(it) { data ->
// custom snackbar with the custom colors
Snackbar(
actionColor = Green,
//contentColor = ...,
snackbarData = data
)
}
},
Then just use it:
scope.launch {
scaffoldState.snackbarHostState.showSnackbar(
message = "Note Deleted",
actionLabel = "Undo"
)
}

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

Get Button Text

I have a Button composable that I need to get the text value when clicked.
Button(
onClick = {// Get the "TheText" from below },
) {
Text(
modifier = Modifier.padding(8.dp),
text = "TheText",
style = TextStyle(fontSize = 15.sp)
)
}
I am creating a type of quiz where the buttons text matches the correct answer.
I thin I may need to create a custom compposabe that takes the text as a parameter and also a callback function that will pass that text back up to my main program where I can Check for a correct answer.
I assume you want to input text instead of just displaying one.
#Composable
fun example() {
var text by remember { mutableStateOf("TheText") }
Column {
Button(
onClick = {
val useThisString = text
},
) { Text(text = text) } // Probably wanna put "Copy" here
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Optinal Label") }
)
}
}
Otherwise, if you just want the label of the button:
val buttonText = "TheText"
Button(
onClick = {
// Use variable here
},
) {
Text(
modifier = Modifier.padding(8.dp),
text = buttonText,
style = TextStyle(fontSize = 15.sp)
)
}
Ok here's how to store it in a variable
var retrievedValue by mutableStateOf("") //Assuming you must use it somewhere else as state
var currentValue by rememberSaveable { mutableStateOf("The Text") }
Button(
onClick = { retrievedValue = currentValue },
) {
Text(
modifier = Modifier.padding(8.dp),
text = currentValue,
style = TextStyle(fontSize = 15.sp)
)
}
Now you can use it anywhere you want. Changing the retrievedValue would trigger recompositions in any composable that reads it.
This should solve your problem. Use the retrievedValue as the value returned by a callback. In compose, for such stuff, you do not need callbacks. MutableState objects, whenever are modified, trigger a recomposition on the composables reading them.
Anyway, here when you click the button, you will get the value of the text, whatever it may be, you will always get the current value.

Do Assistive Text, Error Message, Character Counter exist for Jetpack Compose TextField?

In material design TextField page TextField has properties such as
Assistive elements provide additional detail about text entered into
text fields.
Helper text Helper text conveys additional guidance about the input field, such as how it will be used. It should only take up a single
line, being persistently visible or visible only on focus.
Error message When text input isn't accepted, an error message can display instructions on how to fix it. Error messages are displayed
below the input line, replacing helper text until fixed.
Icons Icons can be used to message alerts as well. Pair them with error messages to provide redundant alerts, which are useful when you
need to design for colorblind users.
Character counter Character or word counters should be used if there is a character or word limit. They display the ratio of
characters used and the total character limit.
Do these properties exist for Jetpack Compose TextField as of compose 1.0.0-alpha09?
With 1.0.x there aren't built-in properties to display an error message or the counter text.
However you can use a custom composable.
For the error message you can use something like:
var text by rememberSaveable { mutableStateOf("") }
var isError by rememberSaveable { mutableStateOf(false) }
fun validate(text: String) {
isError = /* .... */
}
Column {
TextField(
value = text,
onValueChange = {
text = it
isError = false
},
trailingIcon = {
if (isError)
Icon(Icons.Filled.Error,"error", tint = MaterialTheme.colors.error)
},
singleLine = true,
isError = isError,
keyboardActions = KeyboardActions { validate(text) },
)
if (isError) {
Text(
text = "Error message",
color = MaterialTheme.colors.error,
style = MaterialTheme.typography.caption,
modifier = Modifier.padding(start = 16.dp)
)
}
}
To display the counter text you can use something like:
val maxChar = 5
Column(){
TextField(
value = text,
onValueChange = {
if (it.length <= maxChar) text = it
},
modifier = Modifier.fillMaxWidth()
)
Text(
text = "${text.length} / $maxChar",
textAlign = TextAlign.End,
style = MaterialTheme.typography.caption,
modifier = Modifier.fillMaxWidth().padding(end = 16.dp)
)
}
trailingIcon for the icon.
For the text at the bottom I just used
Text(
text = "Error message",
color = MaterialTheme.colors.error,
style = MaterialTheme.typography.caption,
modifier = Modifier.padding(start = 16.dp)
)
Might be included in the future? Weirdly enough the documentation for isError says:
indicates if the text field's current value is in error. If set to
true, the label, bottom indicator and trailing icon by default will
be displayed in error color
What bottom indicator? There is no such thing. Weird.

Categories

Resources