How to change TextStyle in Snackbar with Scaffold? - android

Don't understand how to assign text style to Snackbar
Scaffold(
scaffoldState = scaffoldState,
snackbarHost = { hostState ->
SnackbarHost(hostState = hostState) { data ->
Snackbar(
snackbarData = data,
backgroundColor = MaterialTheme.colors.background,
contentColor = MaterialTheme.colors.onBackground,
actionColor = MaterialTheme.colors.primary
)
}
},
scope.launch {
val result = scaffoldState.snackbarHostState.showSnackbar("Removed from favourites","Cancel")
when(result) {
SnackbarResult.ActionPerformed -> {
viewModelForFavourite.addFavouritePhoto(FavouritePhotosEntity(url = photoUrl))
}
else -> Unit
}
}
i found that Snackbar used body2 TextStyle and button TextStyle in file Type.kt but so many actions i used this two, how i can override this in snackBar?

Can we use do as mentioned below
From
SnackbarHost(hostState = hostState) { data ->
Snackbar(
snackbarData = data,
backgroundColor = MaterialTheme.colors.background,
contentColor = MaterialTheme.colors.onBackground,
actionColor = MaterialTheme.colors.primary
)
}
To
SnackbarHost(hostState = hostState) { data ->
Snackbar(
modifier = Modifier.padding(4.dp),
action = {
TextButton(onClick = {}) {
Text(text = data.message)
}
}
) {
Text(text = "This is a basic Snackbar with action item",)
}
}
if yes then we must have control over Text to make changes as per our requirement

You can use the Snackbar composable with the action and the content as parameter. In this way you can customize the message and the action.
Something like:
snackbarHost = {
SnackbarHost(it) { data ->
// custom snackbar
Snackbar(
modifier = Modifier.padding(8.dp),
action = {
TextButton(
colors = ButtonDefaults.textButtonColors(contentColor = Yellow),
onClick = { },
content = {
Text(
"Action",
style = TextStyle(fontSize = 14.sp),
textDecoration = TextDecoration.Underline
)
}
)
}
) {
Row() {
Icon(Icons.Filled.Warning, "", Modifier.padding(end = 8.dp), tint = Yellow)
Text(
"snackbarData.message",
style = TextStyle(fontSize = 14.sp, fontWeight = FontWeight.Bold),
)
}
}
}
}

Related

How to change TopAppBar height when using Scaffold under Material 3

I am using the Material 3 Scaffold with the material 3 TopAppBar. I need to change the height of TopAppBar but cannot use MediumTopAppBar as it's too heightened. Is there any way to do the same?
Here is the code
val scrollBehaviour = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopAppBar(
title = {
Text(
text = "About",
modifier = Modifier
.padding(start = 30.dp, bottom = 12.dp)
.wrapContentSize(),
color = colorResource(id = R.color.black)
)
},
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = Color.Red,
titleContentColor = Color.Black,
),
modifier = Modifier.fillMaxWidth(),
navigationIcon = {
Button(onClick = { }) {
Text(text = "B1")
}
}, actions = {
Button(onClick = {}) {
Text(text = "B2")
}
},
scrollBehavior = scrollBehaviour
)
},
content = {
}
)

How can I fix my alert dialog in kotlin compose?

I' ve been making a dictionary app for a while and I added that users can create own dictionaries on my app. I show users dictionary on the screen and users can delete their dictionaries whatever they want. so I am trying to make alert dialog for this because I want users not to delete their dictionaries when they press the delete icon directly. An alert dialog will appear on the screen and there should be two buttons such as cancel and accept in that alert dialog. If the user presses accept, that is, if he wants to delete, I want the dictionary to be deleted.
However, the problem is that it is difficult to implement this in compose and in the codes I wrote because I encountered many problems for some reason, whereas it should have been easy. What I did in my codes is that if user clicks delete icon onDeleteClick works and showAlertDialog becomes true in onDeleteClick. When true, it goes inside the top if block and calls the alert dialog component. When the alert dialog compo is called, CustomDialogUI opens. I send two parameters to CustomDialogUI, one is a showAlertDialog mutablestate that controls the opening and closing of the alert dialog, and the second one is deleteDicState if the user says allow in the alert dialog that opens, deleteDicState becomes true and if deleteDicState is true, the deletion must occur.
Since deleteDicState is false the first time, it does not delete, but when the alert dialog opens for the second time and I say delete, it deletes it for some reason. How can i solve this problem help.
my code
#Composable
fun CreateYourOwnDictionaryScreen(
navController: NavController,
viewModel: CreateYourOwnDictionaryViewModel = hiltViewModel()
) {
val scaffoldState = rememberScaffoldState()
val state = viewModel.state.value
val scope = rememberCoroutineScope()
val context = LocalContext.current
val showAlertDialog = remember { mutableStateOf(false) }
val deleteDicState = remember { mutableStateOf(false) }
if(showAlertDialog.value){
Dialog(onDismissRequest = { showAlertDialog.value = false }) {
CustomDialogUI(openDialogCustom = showAlertDialog,deleteDicState)
}
}
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
backgroundColor = bar,
title = {
androidx.compose.material3.Text(
text = "your dictionaries",
modifier = Modifier.fillMaxWidth(),
color = Color.White,
fontSize = 22.sp
)
},
navigationIcon = {
IconButton(onClick = {
navController.navigate(Screen.MainScreen.route)
}) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = "Go Back"
)
}
}
)
},
floatingActionButtonPosition = FabPosition.Center,
floatingActionButton = {
FloatingActionButton(
onClick = { navController.navigate(Screen.CreateDicScreen.route) },
backgroundColor = bar,
) {
Icon(Icons.Filled.Add, "fab")
}
}
) {
Box(modifier = Modifier.background(MaterialTheme.colors.background)) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
items(state.dictionaries) { dictionary ->
CreateYourOwnDictionaryItem(
dictionary = dictionary,
modifier = Modifier
.fillMaxWidth()
.clickable {
navController.navigate(Screen.MyWordsScreen.passDicId(dictionary.uid))
},
onAddClick = {
navController.navigate(
Screen.MakeYourDictionaryScreen.passDicId(
dictionary.uid
)
)
},
onDeleteClick = {
if(deleteDicState.value){
viewModel.onEvent(
CreateYourOwnDictionaryEvents.DeleteDictionary(dictionary)
)
scope.launch {
val result = scaffoldState.snackbarHostState.showSnackbar(
message = "dictionary is deleted",
/*actionLabel = "Undo",*/
duration = SnackbarDuration.Short
)
}
}
},
onEditClick = {
navController.navigate(
Screen.UpdateOwnDictionaryScreen.passDicIdAndDicName(
dictionary.uid,
dictionary.creationTime,
)
)
}
)
}
}
}
}
}
}
#Composable
fun CustomDialogUI(
openDialogCustom: MutableState<Boolean>,
deleteDicState : MutableState<Boolean>
) {
Card(
//shape = MaterialTheme.shapes.medium,
shape = RoundedCornerShape(10.dp),
// modifier = modifier.size(280.dp, 240.dp)
modifier = Modifier.padding(10.dp, 5.dp, 10.dp, 10.dp),
elevation = 8.dp
) {
Column(
modifier = Modifier
.background(Color.White)
) {
//.......................................................................
Image(
painter = painterResource(id = R.drawable.ic_baseline_warning),
contentDescription = null, // decorative
/*contentScale = ContentScale.Fit,
colorFilter = ColorFilter.tint(
color = bar
),*/
modifier = Modifier
.padding(top = 35.dp)
.height(70.dp)
.fillMaxWidth(),
)
Column(modifier = Modifier.padding(16.dp)) {
androidx.compose.material3.Text(
text = "Warning !",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(top = 5.dp)
.fillMaxWidth(),
style = MaterialTheme.typography.body2,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
androidx.compose.material3.Text(
text = "Are you sure that your previously created dictionary will be deleted?",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(top = 10.dp, start = 25.dp, end = 25.dp)
.fillMaxWidth(),
)
}
//.......................................................................
Row(
Modifier
.fillMaxWidth()
.padding(top = 10.dp)
.background(bar),
horizontalArrangement = Arrangement.SpaceAround
) {
TextButton(onClick = {
openDialogCustom.value = false
}) {
Text(
"Not Now",
fontWeight = FontWeight.Bold,
color = Color.Black,
modifier = Modifier.padding(top = 5.dp, bottom = 5.dp)
)
}
TextButton(onClick = {
openDialogCustom.value = false
deleteDicState.value = true
}) {
Text(
"Allow",
fontWeight = FontWeight.ExtraBold,
color = Color.Black,
modifier = Modifier.padding(top = 5.dp, bottom = 5.dp)
)
}
}
}
}
}
I cannot call the CustomDialogUI in onDeleteClick . If I call it, it gives the following error #Composable invocations can only happen from the context of a #Composable function.
for example like this
CreateYourOwnDictionaryScreen
onDeleteClick = {
Dialog(onDismissRequest = { showAlertDialog.value = false }) {
CustomDialogUI(openDialogCustom = showAlertDialog,deleteDicState)
}
....
I cannot call like this.
So I call it outside of onDeleteClick. or directly in CustomDialogUI if the user presses the delete button, I cannot delete it there because I can't access viewmodel and dictionary there
for example like this
CustomDialogUI
TextButton(onClick = {
openDialogCustom.value = false
viewModel.onEvent(
CreateYourOwnDictionaryEvents.DeleteDictionary(dictionary)
)
scope.launch {
val result = scaffoldState.snackbarHostState.showSnackbar(
message = "dictionary is deleted",
/*actionLabel = "Undo",*/
duration = SnackbarDuration.Short
)
}
}) {
Text(
"Allow",
fontWeight = FontWeight.ExtraBold,
color = Color.Black,
modifier = Modifier.padding(top = 5.dp, bottom = 5.dp)
)
}
}
I cannot call like this.
Passing MutableStates as composable parameters is considered a bad practice, you should pass raw values and callbacks instead. In your case, you can implement it like this:
#Composable
fun CreateYourOwnDictionaryScreen() {
val showDeleteDialogForItem = remember { mutableStateOf<DictionaryItem?>(null) }
showDeleteDialogForItem.value?.let { itemToDelete ->
DeleteDialog(
onDeleteConfirm = {
viewModel.onEvent()
showDeleteDialogForItem.value = null
},
onCancel = { showDeleteDialogForItem.value = null },
)
}
...
items.forEach { item ->
CreateYourOwnDictionaryItem(
onDeleteClick = { showDeleteDialogForItem.value = item }
)
}
}
#Composable
fun DeleteDialog(
onDeleteConfirm: () -> Unit,
onCancel: () -> Unit,
) {
...
Button(onClick = onCancel) { Text("Cancel") }
Button(onClick = onDeleteConfirm) { Text("Delete") }
}

CenterAlignedTopAppBar won't scroll. What am I doing wrong?

I am trying to add a scrollable behavior to the topBar parameter of Scaffold. In the documentation it says, that I can add the scrollable behavior by setting the CenterAlignedTopAppBar parameter scrollBehavior. However it doesn't seem to work.
The following answer from StackOverflow didn't help.
Any advice appreciated.
Here is how my code goes.
#Composable
fun Screen() {
val topAppBarScrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(
rememberTopAppBarState(),
{ true },
spring(Spring.StiffnessMediumLow),
rememberSplineBasedDecay()
)
val scrollBehavior = remember { topAppBarScrollBehavior }
Scaffold(
topBar = {
ThemedTopBar(scrollBehavior, title = "Select Guests", onBack = {/* TODO */})
}
) { innerPadding ->
//MainContent(innerPadding)
}
}
#Composable
fun ThemedTopBar(scrollBehavior: TopAppBarScrollBehavior, title: String, onBack: () -> Unit) {
CenterAlignedTopAppBar(
modifier = Modifier
.height(51.dp)
.padding(vertical = 16.dp, horizontal = 9.dp)
,
title = {
Text(
text = title,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = Typography.titleMedium
)
},
navigationIcon = {
IconButton(
modifier = Modifier.size(22.dp),
onClick = onBack,
) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_arrow_back),
contentDescription = "Back Button",
tint = ThemeBlue
)
}
},
scrollBehavior = scrollBehavior
)
}
You have to attach the TopAppBarScrollBehavior.nestedScrollConnection to a Modifier.nestedScroll in order to keep track of the scroll events.
Something like:
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
CenterAlignedTopAppBar(
title = { /* .. */ },
navigationIcon = { /* .. */ },
actions = { /* .. */ },
scrollBehavior = scrollBehavior
)
},
content = { /* .. */ }
)

Update LazyColumn after remove opertation in KMM JetpackCompose app

I was deveoping an Kotlin Multiplatform app, where I develop the UI using Jetpack Compose framework, where I recover some data from network using graphql, to keep it into a local database build with SQLDelight.
My poblem comes when I try to implement a remove operation into my localDatabase, due to the LazyColumn component doesn't update after remove some item.
I saw there are some solution using SnapshotStateList, but I don't see how to implemented, and I try to do it using a mutableState of a boolean variable, which tells me if there some change which need to be update, but the Composable doesn't recompose neither.
this is my main component where I added the list:
#Composable
fun MyCharactersView(viewModel: MainViewModel, bottomBar: #Composable () -> Unit, popBack: () -> Unit, navController: NavController, characterSelect: (character: CharacterModel) -> Unit) {
val isLoading = viewModel.isLoading.collectAsState()
val loadError = viewModel.loadError.collectAsState()
val charactersBought = viewModel.characterBought.collectAsState()
val charactersBoughtSnapShot : SnapshotStateList<List<CharacterModel>> = SnapshotStateList(charactersBought.value)
LaunchedEffect(key1 = Unit){
viewModel.getAllBoughtCharacters().also {
Log.d("info", "Lanza el getAllBoughtCharacters:count: ${charactersBought.value.size}")
}
}
when {
isLoading.value -> {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator(
color = MaterialTheme.colors.primary,
modifier = Modifier
.fillMaxWidth(0.4f)
.fillMaxHeight(0.4f)
.align(Alignment.Center)
)
}
}
loadError.value != "" -> {
Text(
text = "Se ha producido un error",
color = Color.Red,
textAlign = TextAlign.Center
)
}
else -> {
if(viewModel.updateList.value){
viewModel.getAllBoughtCharacters().also {
Log.d("info", "Llama al viewModel.updateList.value: ${charactersBought.value}")
}
}
Scaffold(
topBar = {
TopAppBar(
title = { Text(
text = "MyCharacters",
style = TextStyle(
color = Color.White,
fontStyle = FontStyle.Italic,
textAlign = TextAlign.Center
)
)},
navigationIcon = {
IconButton(onClick = { popBack() }) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Back")
}
}
)
},
bottomBar = bottomBar)
{ paddingValues ->
Surface(
modifier = Modifier
.background(
Color.Transparent
)
) {
if(charactersBought.value.isEmpty()){
Text(
text = "You don't have any character jet.\nTry to buy some one",
fontStyle = FontStyle.Italic,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
modifier = Modifier.padding(start = (LocalConfiguration.current.screenWidthDp/4).dp, end = 0.dp, top = (LocalConfiguration.current.screenHeightDp/4).dp)
)
}else{
LazyColumn(
contentPadding = paddingValues,
modifier = Modifier
.background(Color.Transparent)
) {
Log.d("info", "CharacterResponse in items function: ${charactersBought.value}")
items(charactersBought.value) { character ->
MyCharactersListRowView(
navController = navController,
viewModel = viewModel,
characterModel = character!!,
characterSelected = characterSelect
)
}
}
}
}
}
}
}
}
And this is my ListRow component:
#OptIn(ExperimentalFoundationApi::class)
#Composable
fun MyCharactersListRowView(
navController: NavController,
viewModel: MainViewModel,
characterModel: CharacterModel,
characterSelected: (character : CharacterModel) -> Unit
) {
val openDialog = remember { mutableStateOf(false) }
if(openDialog.value) {
SimpleAlertDialog(
show = true,
onConfirm = { viewModel.deleteCharacter(characterModel.id.toLong().also {
if(viewModel.rowAffected.value.toInt() != 0) {
Toast.makeText(appContext, "${characterModel.name} remove correctly !", Toast.LENGTH_LONG).show().also {
openDialog.value = false
viewModel.updateList.value = true
}
}
}) },
onDismiss = { openDialog.value = false },
textDescription = "Would you like to remove ${characterModel.name} from your characters?",
textTittle = "Remove"
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = { characterSelected(characterModel) })
.padding(vertical = 8.dp, horizontal = 16.dp)
.combinedClickable(
onLongClick = {
openDialog.value = true
},
onClick = {
navController.navigate(Screens.CharacterDetailsScreen.route + "/${characterModel.id}")
}
),
verticalAlignment = Alignment.CenterVertically
){
AsyncImage(
model = characterModel.image,
contentDescription = characterModel.name,
contentScale = ContentScale.Fit,
modifier = Modifier
.size(60.dp)
.clip(CircleShape)
)
Column(modifier = Modifier.weight(1F)) {
Text(
text = characterModel.name,
style = MaterialTheme.typography.h5,
fontWeight = FontWeight.Bold
)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) {
Text(
text = "Seen in ${characterModel.numberEpisodes} episodes, most frequently in ${characterModel.location}",
style = MaterialTheme.typography.body1,
fontWeight = FontWeight.Thin
)
}
}
}
Divider()
}
So if you knows some way to force to recompose a composable, (which I think is not possible), or a working solution using the SnapShotStateList, and can share, take thanks in advance !

How to replace the content of a TopAppBar dynamically?

Imagine I have a TopAppBar (1) like
In Code similar to:
TopAppBar(
backGroundColor = Colors.black
) {
Row(modifier = Modifier) {
Icon( // 2
modifier = Modifier.size(24.dp),
id = R.drawable.ic_hamburger_menu,
onClick = {
openMenu()
}
)
Text( // 3
modifier = Modifier,
text = "Page Title"
)
Icon( // 4.1
modifier = Modifier.size(24.dp),
id = R.drawable.ic_share,
onClick = {
//..
}
)
Icon( // 4.2
modifier = Modifier.size(24.dp),
id = R.drawable.ic_magnifing_glass,
onClick = {
openTopAppBarWithSearchContent()
}
)
Icon( // 5
modifier = Modifier.size(24.dp),
id = R.drawable.ic_ellipsis,
onClick = {
//..
}
)
}
}
When cliking on the magnifier glass (4.2), I would like to replace the complete (1) content (Manu icon, Text, Share icon, glass icon, points icon) of the top app bar with an individual Composable; let's say a search/input field..
With other words: openTopAppBarWithSearchContent() should replace its parent TopAppBars content.
How can this be realized in a Jetpack Compose way?
You can use a mutableState to change your layout based on state value. When you change state value it will trigger a recomposition and based on current value recomposition will pick desired layout.
#Composable
fun MyTopAppBar(
backGroundColor: Color = MaterialTheme.colors.primary
) {
var showFirstMenu by remember { mutableStateOf(true) }
if (showFirstMenu) {
Row(
modifier = Modifier
.background(MaterialTheme.colors.primary)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
// 2
IconButton(onClick = { /*TODO*/ }) {
Icon(imageVector = Icons.Filled.Menu, contentDescription = null, tint = Color.White)
}
Text( // 3
modifier = Modifier,
text = "Page Title",
color = Color.White
)
Spacer(modifier = Modifier.weight(1f))
// 4.1
IconButton(onClick = { /*TODO*/ }) {
Icon(
imageVector = Icons.Filled.Share,
contentDescription = null,
tint = Color.White
)
}
// 4.2
IconButton(onClick = { showFirstMenu = !showFirstMenu }) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = null,
tint = Color.White
)
}
// 5
IconButton(onClick = { /*TODO*/ }) {
Icon(
imageVector = Icons.Filled.MoreVert,
contentDescription = null,
tint = Color.White
)
}
}
} else {
TopAppBar(
title = { Text("Another Page") },
navigationIcon = {
IconButton(onClick = {}) {
Icon(Icons.Default.Menu, "Menu")
}
},
actions = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Favorite, contentDescription = null)
}
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Refresh, contentDescription = null)
}
IconButton(
onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Call, contentDescription = null)
}
}
)
}
}
And you can TopAppbar instead of Row to create one.

Categories

Resources