Toast Doesn't show in jetpack compose project - android

So i began learning jetpack compose and i started following a simple tutorial on youtube to list Harry Potter actors in a LazyColumn.
However, i was not able to display a simple Toast message by passing the actors name as a Lambda PArameter as shown below :
#Composable
fun HomeScreen(context: Context) {
val viewModel = getViewModel<HomeViewModel>()
val state by viewModel.state.collectAsState()
LazyColumn {
if (state.isEmpty()) {
item {
CircularProgressIndicator(
modifier = Modifier
.fillMaxSize()
.wrapContentSize(align = Alignment.Center)
)
}
} else {
items(state) { character ->
CharacterImageCard(character) {
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
Log.e("TAG", "HomeScreen:$it ", )
}
}
}
}
}
PS: note that theres a Log.e, it prints the characters name just fine.
heres the Character Image card
#Composable
fun CharacterImageCard(character: CharactersItemX, selectedItem: (String) -> Unit) {
val imagePainter = rememberImagePainter(data = character.image)
Card(
shape = MaterialTheme.shapes.medium,
modifier = Modifier
.padding(16.dp)
) {
Row(Modifier.clickable(onClick = { selectedItem(character.name) })) {
Box {
Image(
painter = imagePainter,
contentDescription = character.name,
modifier = Modifier
.fillMaxWidth()
.height(200.dp),
contentScale = ContentScale.Fit,
)
Surface(
color = MaterialTheme.colors.primary.copy(alpha = 0.5f),
modifier = Modifier
.align(Alignment.BottomCenter),
contentColor = MaterialTheme.colors.surface
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(4.dp)
) {
Text(
text = character.name,
style = MaterialTheme.typography.h6
)
Text(
text = character.house,
style = MaterialTheme.typography.body2
)
}
}
}
}
}
}
I call HomeScreen on my MainActivty

Example:
#Composable
fun HomeScreen(context: Context) {
val viewModel = getViewModel<HomeViewModel>()
val state by viewModel.state.collectAsState()
// use localContext
val localContext = LocalContext.current
LazyColumn {
if (state.isEmpty()) {
item {
CircularProgressIndicator(
modifier = Modifier
.fillMaxSize()
.wrapContentSize(align = Alignment.Center)
)
}
} else {
items(state) { character ->
CharacterImageCard(character) {
Toast.makeText(localContext, it, Toast.LENGTH_SHORT).show()
Log.e("TAG", "HomeScreen:$it ", )
}
}
}
}
}

I reproduced your code and Toast works fine. I don't know what's the problem, maybe try getting context from composable instead of passing it from the main activity.

Related

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

How to Successfully navigate from ListItem screen to Details Screen (Jetpack Compose)

I'm praticing Compose navigation. I made an App that displays a ListItem with images, on what I call HomeScreen, when a particular item is clicked it navigates to a destination containing more information/ Details, on what I called HomeInfoScreen. And to do this I used Navigation compose Arugments. I basically did this by benchmarking the Android Developers Rally Compose.
But the problem is whenever I click on any of the rows it takes me to the details of the first Item, no matter which of them I click.
I believe the problem is from coming from HomeScreen (remember, I said this was the destination I'm navigating from)
I've previously researched, and got an Idea of passing my model object as a parameter.
But I think I did something wrong, because I get errors, and I don't know how to fix it.
Please understand that I arranged the code, in multiple composables, in this format;
SecondBodyElement -> SecondBodyGrid ------> HomeContentScreen
And Finally I call HomeContentScreen on the HomeScreen.
SecondBodyElement;
#Composable
fun SecondBodyElement(
#StringRes text: Int,
#DrawableRes drawable: Int,
modifier: Modifier = Modifier,
onHomeCardClick: (Int) -> Unit
) {
Surface(
shape = MaterialTheme.shapes.small,
elevation = 10.dp,
modifier = modifier
.padding(horizontal = 12.dp, vertical = 12.dp)
.clip(shape = RoundedCornerShape(corner = CornerSize(8.dp)))
.clickable { onHomeCardClick(drawable) }
) {
Column(
horizontalAlignment = Alignment.Start,
modifier = Modifier
) {
Image(
painter = painterResource(drawable),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
)
Text(
text = stringResource(text),
style = MaterialTheme.typography.h3,
maxLines = 3,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 16.dp)
)
}
}
}
SecondyBodyGrid;
#Composable
fun SecondBodyGrid(
onHomeCardClick: (Int) -> Unit = {},
) {
LazyVerticalGrid(
columns = GridCells.Fixed(1),
contentPadding = PaddingValues(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier
.height(1450.dp)
//.disabledVerticalPointerInputScroll()
) {
items(SecondBodyData) { item ->
SecondBodyElement(
onHomeCardClick = onHomeCardClick,
drawable = item.drawable,
text = item.text,
modifier = Modifier
.height(380.dp)
.clickable { onHomeCardClick(item.drawable + item.text) }
)
}
}
}
HomeContentScreen;
#Composable
fun HomeContentScreen(
modifier: Modifier = Modifier,
onHomeCardClick: (String) -> Unit,
accountType: String? = HomeInfoModel.homeInfoModelList.first().title
) {
val homeInfo = remember(accountType) { HomeInfoModel.getHomeInfo(accountType) }
Column(
modifier
.verticalScroll(rememberScrollState())
.padding(vertical = 16.dp)
) {
HomeQuote()
HomeTitleSection(title = R.string.favorite_collections) {
SecondBodyGrid { onHomeCardClick(homeInfo.title) }
}
}
}
And Finally HomeScreen;
#Composable
fun HomeScreen(onHomeCardClick: (String) -> Unit) {
HomeContentScreen(onHomeCardClick = onHomeCardClick)
}
Please like I said I'm practicing, I don't know what you are going to need. But I'm going to add my NavHost (Nav Graph) and the Model file, just incase, If you need any other thing I'm more than happy to provide.
Model, HomeInfoModel;
data class HomeInfoData(
val id: Int,
val title: String,
val sex: String,
val age: Int,
val description: String,
val homeInfoImageId: Int = 0
)
object HomeInfoModel {
val homeInfoModelList = listOf(
HomeInfoData(
id = 1,
title = "There's Hope",
sex = "Male",
age = 14,
description = "Monty enjoys chicken treats and cuddling while watching Seinfeld.",
homeInfoImageId = R.drawable.ab1_inversions
),
....
)
fun getHomeInfo(accountName: String?): HomeInfoData {
return homeInfoModelList.first { it.title == accountName }
}
}
My NavHost (Nav Graph);
....
composable(route = Home.route) {
HomeScreen(
onHomeCardClick = { accountType ->
navController.navigateToHomeInfoScreen(accountType)
}
)
}
composable(
route = HomeInfoDestination.routeWithArgs,
arguments = HomeInfoDestination.arguments,
) { navBackStackEntry ->
// Retrieve the passed argument
val accountType =
navBackStackEntry.arguments?.getString(HomeInfoDestination.accountTypeArg)
// Pass accountType
HomeInfoScreen(accountType)
}
....
}
}
....
private fun NavHostController.navigateToHomeInfoScreen(accountType: String) {
this.navigateSingleTopTo("${HomeInfoDestination.route}/$accountType")
}
I think the problem is from the Homescreen but I don't really know, So I'm going to Add the HomeInfoScreen, Sorry making this question any longer.
HomeInfoScreen;
#Composable
fun HomeInfoScreen(
accountType: String? = HomeInfoModel.homeInfoModelList.first().title
) {
DisplayHomeInfo(accountType)
}
#Composable
fun WelcomeText() {
Text(
text = "Welcome, to Home Information",
style = MaterialTheme.typography.h3,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 18.dp)
)
}
#Composable
fun HomeInfoDetails(
accountType: String? = HomeInfoModel.homeInfoModelList.first().title
) {
val homeInfo = remember(accountType) { HomeInfoModel.getHomeInfo(accountType) }
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
) {
Image(
painter = painterResource(id = homeInfo.homeInfoImageId),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.clip(shape = RoundedCornerShape(topEnd = 4.dp, bottomEnd = 4.dp)),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = homeInfo.title,
style = MaterialTheme.typography.h3
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = homeInfo.description,
style = MaterialTheme.typography.h5
)
}
}
// Step: Home screen - Scrolling
#Composable
fun DisplayHomeInfo(
accountType: String? = HomeInfoModel.homeInfoModelList.first().title
) {
Column(
Modifier
.verticalScroll(rememberScrollState())
.padding(vertical = 16.dp)
) {
WelcomeText()
HomeInfoDetails(accountType)
}
}
For Clarity Sake; How can I navigate to the exact item when it is clicked on the SuccessScreen.
I'll sinerely be greatful for any help. Thanks a lot in advance for your help.
In case somebody needs this, I've been able to do this. I followed a website's Developer's Breach tutorial.

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 !

dynamically change text in cards - Jetpack Compose state

New to Compose and struggling hard with more complex state cases.
I cant seem to change the text dynamically in these cards, only set the text manually. Each button press should change the text in a box, starting left to right, leaving the next boxes empty.
What is wrong here?
UI:
val viewModel = HomeViewModel()
val guessArray = viewModel.guessArray
#Composable
fun HomeScreen() {
Column(
modifier = Modifier
.fillMaxWidth()
) {
WordGrid()
Keyboard()
}
}
#Composable
fun WordGrid() {
CardRow()
}
#Composable
fun Keyboard() {
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
MyKeyboardButton(text = "A", 35)
MyKeyboardButton(text = "B", 35)
}
}
#Composable
fun MyCard(text: String) {
Card(
modifier = Modifier
.padding(4.dp, 8.dp)
.height(55.dp)
.aspectRatio(1f),
backgroundColor = Color.White,
border = BorderStroke(2.dp, Color.Black),
) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
text = text,
fontSize = 20.sp,
)
}
}
}
#Composable
fun CardRow() {
guessArray.forEach { rowCards ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
rowCards.forEach {
MyCard(it)
println(it)
}
}
}
}
#Composable
fun MyKeyboardButton(text: String, width: Int) {
Button(
onClick = {
guessArray[viewModel.currentRow][viewModel.column] = text
viewModel.column += 1
},
modifier = Modifier
.width(width.dp)
.height(60.dp)
.padding(0.dp, 2.dp)
) {
Text(text = text, textAlign = TextAlign.Center)
}
}
ViewModel:
class HomeViewModel : ViewModel() {
var currentRow = 0
var guessArray = Array(5) { Array(6) { "" }.toMutableList() }
var column = 0
}
The grid is created, but the text is never changed.
To make Compose view recompose with the new value, a mutable state should be used.
You're already using it with remember in your composable, but it also needs to be used in your view model for properties, which should trigger recomposition.
class HomeViewModel : ViewModel() {
var currentRow = 0
val guessArray = List(5) { List(6) { "" }.toMutableStateList() }
var column = 0
}

Jetpack Compose: IntrinsicMeasurements not supported loading with Accompanist CoilImage in DropdownMenu

I want to build a dropdown menu with items that contain not only text, but also an image. The image should be loaded from an url. I'm using Dropdown Menu and Accompanist to load the image.
But when I try to open the Dropdown Menu, I get java.lang.IllegalStateException: Intrinsic measurements are not currently supported by SubcomposeLayout.
I've tried to play around with Intrinsics in my Composables like here https://developer.android.com/codelabs/jetpack-compose-layouts#10, but it didn't work. If I don't use CoilImage, but get a painter from resources with Image, everything works fine.
Is there a way to solve it?
#Composable
fun DropdownChildren(
items: List<ChildUiModel>,
chosenChild: ChildUiModel?,
onChildChosen: (ChildUiModel) -> Unit
) {
var expanded by remember { mutableStateOf(false) }
var selectedIndex by remember { mutableStateOf(0) }
Box(modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.TopStart)) {
Row(modifier = Modifier
.fillMaxSize()
.clickable(onClick = { expanded = true })) {
ChildrenDropdownMenuItem(
imageUrl = "https://oneyearwithjesus.files.wordpress.com/2014/09/shutterstock_20317516.jpg",
text = items[selectedIndex].name?: "No name",
chosen = false)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier
.fillMaxWidth()
.requiredSizeIn(maxHeight = 500.dp)
) {
items.forEachIndexed { index, child ->
DropdownMenuItem(
modifier = Modifier
.background(color = if (child.id == chosenChild?.id) appColors.secondary else appColors.primary),
onClick = {
expanded = false
selectedIndex = index
onChildChosen(items[selectedIndex])
}) {
ChildrenDropdownMenuItem(
imageUrl = "https://oneyearwithjesus.files.wordpress.com/2014/09/shutterstock_20317516.jpg",
text = child.name,
chosen = child.id == chosenChild?.id)
}
}
}
}
}
#Composable
fun ChildrenDropdownMenuItem(
imageUrl: String,
text: String,
chosen: Boolean
){
Row(){
Avatar(url = imageUrl)
Text(text = text,
style = AppTheme.typography.h4,
color = if (chosen) appColors.primary else appColors.secondary,
modifier = Modifier
.fillMaxWidth()
.align(Alignment.CenterVertically))
}
}
#Composable
fun Avatar(
url: String
){
val contentPadding = PaddingValues(8.dp, 8.dp, 12.dp, 8.dp)
CoilImage(
data = url,
) { imageState ->
when (imageState) {
is ImageLoadState.Success -> {
MaterialLoadingImage(
result = imageState,
contentDescription = "avatar",
modifier = Modifier
.padding(contentPadding)
.clip(CircleShape)
.size(48.dp),
contentScale = ContentScale.Crop,
fadeInEnabled = true,
fadeInDurationMs = 600,
)
}
is ImageLoadState.Error -> CoilImage(
data = "https://www.padtinc.com/blog/wp-content/uploads/2020/09/plc-errors.jpg",
contentDescription = "error",
contentScale = ContentScale.Crop,
modifier = Modifier
.padding(contentPadding)
.clip(CircleShape)
.size(48.dp)
)
ImageLoadState.Loading -> CircularProgressIndicator()
ImageLoadState.Empty -> {}
}
}
}
CoilImage is now Deprecated,
use this
Image(
painter = rememberCoilPainter("https://picsum.photos/300/300"),
contentDescription = stringResource(R.string.image_content_desc),
previewPlaceholder = R.drawable.placeholder,
)
As you mentioned on the bug, this has already been fixed in v0.8.0 of Accompanist. You need to use the new rememberCoilPainter() though, and not the deprecated CoilImage().

Categories

Resources