last day (15 days later) » 

7:22 AM
1
A: How to make dialog components reusable in Jetpack Compose

ThracianIn Jetpack Compose you can make anything reusable using slot api as default Compososables do. @Composable fun MyDialog( onDismissRequest: () -> Unit, title: @Composable () -> Unit, text: @Composable () -> Unit, dismissButton: @Composable () -> Unit, onConfirm: (String)->Unit )...

 
Great (see my Update code), and what is the correct way to call that dialog? The latest code will cause the @Composable invocations can only happen from the context of a @Composable function error
 
@wbk727 have you checked updated answer?
 
Great but bear in mind that not all items in my LazyColumn will open a dialog when clicked.
 
you can set any property of your items null like navigation id for instance, or even onClick nullable for some items and make ` showDialogOption = DialogOption.NewDialog(dessert)` conditional for your items.
 
Where would I specify different values for the properties of MyDialog when different list items are clicked?
 
7:22 AM
MyDialog is just a simple template. You can customize it as needed. For instance you always have the same layout for Text, instead of having ` text: @Composable () -> Unit` parameter have a text:String, also if you always have an image imageBitmap: ImageBitmap, etc. You should design MyDialog how your general properties will be. I put it as an example so you can see that you can have a Composable with value or Composable parameters. For instance you might not need dismiss button for some items create it as ` dismissButton: @Composable () -> Unit={}` which adds no button.
 
Interesting. Please provide the correct way to show text in each list item.
 
Mate, you are unbelieble. You edited my answer so you can un-upvote? I posted a generic answer that only requires a little bit change to make work, even added sample data class that displays how to make it work. What do you mean show text in each item? You just need to change text = { /*TODO*/ } to text:String parameter of MyDialog .
I don't know how your data classes work, so i posed a generic answer. The reason listener approach doesn't work is because you can't call a Composable from scope that doesn't have @Composable annotation. So you need to add clickable with a state that needs to trigger recomposition. and with new State value you can open a Dialog selectively. Which is done by a Boolean flag by defalut. Since yo want more customized Dialog you need to have more stateful value that' why DialogOption is needed.
 
I'm able to continue in chat, text:String is not correct.
 
Now you are able to open dialog via click, now you need to do it selectively for your Items . In onClick of MyDessertRow provided you can check which type of dessert it is and which action you want to take. If it's an item you want to show dialog you set ` showDialogOption = DialogOption.NewDialog(dessert)` and pass required info for dialog such as dessert title, image, navigation string, if you want to open one. Now you are able to trigger a recomposition that can open a Dialog
 
showDialogOption has an error and changing it to var will still give a different error. Val cannot be reassigned
 
7:22 AM
What's the error you get? In my answer it's as var showDialogOption:DialogOption by remember { mutableStateOf(DialogOption.None). It needs to be var to be mutable
 
The error is Type 'TypeVariable(T)' has no method 'setValue(Nothing?, KProperty<*>, DialogOption)' and thus it cannot serve as a delegate for var (read-write property). I can also show any part of my code in the chat.
hello, I think my colleague was the one who un-upvoted your answer, I apologise for that
 
import androidx.compose.runtime.*
search stackoverflow for importing delegate for jetpack Copmpose
106
Q: Type 'State<List<User>?>' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate

SNMI'm trying to get a value from LiveData with observeAsState in jetpack compose, but I get a weird error Type 'State<List?>' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate Code @Composable fun UserScreen(userViewModel:UserViewModel){ val items: List<User

 
@Thracian this worked so thank you
 
because you copied code it used items with int
 
i.e. that particular import
@Thracian oh damn, okay, Sneaky android studio compiler
 
7:29 AM
yes. It imports wrong one for the items tooo
Now you have a list that works.
Dialog is generic one as i said you need to have one that suits your requirements
 
the errors are still there, these are the improts I used:
 
for remember or items?
 
items
i.e. desserts and dessert
 
type items
and select overload with items(list)
as i said above since you copied code you pick the one with int overload
or
                items(items =desserts) { dessert ->
                    MyDessertRow(dessert = dessert,
                        onClick = {
                            showDialogOption = DialogOption.NewDialog(dessert)
                        }
                    )
                }
this is basics for LazyColumn.
You should be able to create a LazyColumn with items of your model
then you need to create a customized dialog
32
Q: Show custom alert dialog in Jetpack Compose

Rohit JakharI am searching how create custom dialog in Jetpack Compose. In XML or Material Design we can create easily custom Dialog in which we can take user input, radio button etc. but i am not finding such thing in Jetpack Compose.

you can check this link to have some ideas about how to create your dialog based on your ui and model
 
would I change the type in this scneario?
 
7:39 AM
Yes. of course.
You need to use your data Items
and to display in LazyColumn you should use your own UI composable instead of MyDessertRow
I suggest you to watch a video about how to create a LazyColumn with your items if you don't have any experience
 
I chnaged the Dessert to this because the app apeared blank before: data class Dessert(val id: Int, val name: String)
 
It should be blank because as you can see
@Composable
private fun MyDessertRow(
dessert: Dessert, onClick: () -> Unit
) {
// Some Row, Column, Etc
}
is an empty Composable. You need to have your own Composables to display in a list
    LazyColumn(modifier = Modifier.padding(it),
      lazyItems = arrayOf(Items.ItemStaters, Items.ItemDesserts),
      onClickItem = myListener) {
      Text(text = stringResource(id = it.textResId))
    }
and LazyColumn doesn't have these params
especially not onClickItem
 
I was using enum before and it worked fine but my circumstances changed where i wanted to use a dialog.
dessert is now in grey
 
Yes, beacuse you don't use it anywhere. These are basic things, i can't explain such simple steps. Please watch video or at least take Codelab's compose tutorials
LazyColumn(modifier = Modifier.padding(it),
lazyItems = arrayOf(Items.ItemStaters, Items.ItemDesserts),
onClickItem = myListener) {
Text(text = stringResource(id = it.textResId))
}
This is not default LazyColum function
 
I know so I used an enum class because I wanted different things to happen when different items were clicked
 
7:49 AM
listener that contains Composable doesn't work because you can't call a composable inside a listener. The way you do is triggering a recomposition with updated value. That's why you need a showDialogOption
 
Okay. Now when you click you need to open a dialog. First start with default dialog ok?
 
that makes more sense, but the part that confused me from the beginning is where to put the text I want in the dialog but for now (for your records):
 
great
now you can customize your dialog to be a generic one for your data set
@Composable
private fun CustomDialogWithResultExample(
onDismiss: () -> Unit,
onNegativeClick: () -> Unit,
onPositiveClick: (Color) -> Unit
) {
var red by remember { mutableStateOf(0f) }
var green by remember { mutableStateOf(0f) }
var blue by remember { mutableStateOf(0f) }

val color = Color(
red = red.toInt(),
green = green.toInt(),
blue = blue.toInt(),
alpha = 255
)

Dialog(onDismissRequest = onDismiss) {

Card(
elevation = 8.dp,
shape = RoundedCornerShape(12.dp)
) {

Column(modifier = Modifier.padding(8.dp)) {
this is my custom dialog for instance
 
7:56 AM
title is Composable by default for AlertDialog
let me do a dialog for you ok
 
ok
 
@Composable
fun MyDialog(
    onDismissRequest: () -> Unit,
    title: String,
    text:String,
    url:Int,
    dismissButton: @Composable () -> Unit,
    onConfirm: (String)->Unit
) {
    AlertDialog(
        onDismissRequest = onDismissRequest,
        title ={
               Text(title)
        },
        text = {
               Column(){
                   Image(painter = painterResource(id = url), contentDescription = "")
                   Text(text)
               }
        },
        dismissButton = dismissButton,
see, when you need to have title or text as String you need to put it inside a Composable
You need to customize your dialog based on your requirements
            MyDialog(
                onDismissRequest = {

                },
                title= "My Tiele",
                url=R.drawable.landscape1,
                text = "My Text",
                dismissButton = {
                    Button(onClick = { /*TODO*/ }) {

                    }
                },
                onConfirm = {navigationLink:String->

                }
            )
and use it like this
point is to design it so you need to duplicate dialog code again
if you don't change button type, color etc go with String, Int params
but if they change use @Composable params
see dismissButton i made it a button
if i want i can change it to a outlined button as
                MyDialog(
                    onDismissRequest = {

                    },
                    title= "My Tiele",
                    url=R.drawable.landscape1,
                    text = "My Text",
                    dismissButton = {
                        OutlinedButton(onClick = { /*TODO*/ }) {

                        }
                    },
                    onConfirm = {navigationLink:String->

                    }
                )
You can use Int, String, Composle, or even colors or fonts as paramaters depends on how generic you want your dialog to be
@Composable
fun MyDialog(
    onDismissRequest: () -> Unit,
    title: String,
    text:String,
    textColor: Color = MaterialTheme.colors.primary,
    url:Int,
    dismissButton: @Composable () -> Unit,
    onConfirm: (String)->Unit
) {
    AlertDialog(
        onDismissRequest = onDismissRequest,
        title ={
               Text(title)
        },
        text = {
               Column(){
                   Image(painter = painterResource(id = url), contentDescription = "")
                   Text(text, color = textColor)
See, now i pass textColor that can be changed
This is what you should do. Decide how generic you want your dialog to be.
 
the dialog is not closing when i click the button
i am currently investigating
 
it's easy
because you have to set showDialogOption onDismissRequet
val openDialog = remember { mutableStateOf(true) }
var text by remember { mutableStateOf("") }

if (openDialog.value) {
    AlertDialog(
        onDismissRequest = {
            openDialog.value = false
        },
        title = {
            Text(text = "Title")
        },
        text = {
            Column() {
                TextField(
                    value = text,
                    onValueChange = { text = it }
                )
                Text("Custom Text")
                Checkbox(checked = false, onCheckedChange = {})
see this example sets openDialog.value = false
you need to set it to DialogOption.None
Compose runs with states
when you change a State recomposition is triggered. So with some eventes, clicks, etc. you change a state and your UI goes to that state
I hope it's clear now
MyDialog(
                onDismissRequest = {
                showDialogOption = DialogOption.None
                },
 
8:12 AM
checking
still not closing, I think I missed something out, apologies, my screen is small
 
It closes now when you click space outside dialog right?
 
yes, but not the button itself
 
it currently doesn't close because we don't call when button is clicked
        MyDialog(
            onDismissRequest = {
                showDialogOption = DialogOption.None
            },
            title= "My Title",
            url=R.drawable.landscape1,
            text = "My Text",
            dismissButton = {
                OutlinedButton(onClick = { showDialogOption = DialogOption.None}) {

                }
            },
            onConfirm = {navigationLink:String->
                showDialogOption = DialogOption.None
            }
        )
That's what i can answer for now. These are basics. If you check some course and videos you will be familiar with these. Design your Dialog based on your requirements and it will work fine
 
that makes sense
thank you for your help
 
You are welcome. Have a good sunday
 
8:19 AM
you too
would I create my navigation links in the Dessert class too?
 

last day (15 days later) »