LazyColumn does not fit to its contents in dialog

Viewed 1334

I have a LazyColumn Inside a Dialog , inside a Simple Column which also contains a row of buttons (Cancel & Set) at the end of the dialog , Previously I was using weight(1f) modifier on the LazyColumn to occupy most of the height of the dialog then giving remaining space to the row of buttons but the problem is weight modifier causes the list to expand full height even if its empty and if I don't set weight modifier then When the contents of the LazyColumn exceed LazyColumn starts occupying full height of the column and the row of buttons cannot be found even upon scrolling.

I want to make it so that my row of buttons is aligned to the bottom of the dialog and LazyColumn takes as much height as its contents without taking space of row of buttons.

Here's my code

Column{
    LazyColumn(modifier = Modifier.weight(1f)){
       items(myItems){ item->
          DisplayItem(item)
       }
    }
    Row{
       Button{}
       Button{}
    }
}
2 Answers

Since the row of buttons must always be visible , The alert dialog provides a composable to add buttons into it , We can use that implementation

You can try changing the number of items to see the problem , In the second case when the number of items exceeds and scrolling must be done , row of buttons is not visible on screen even though it should be !

This will work (not ideal)

AlertDialog(
    onDismissRequest = { /*TODO*/ },
    text = {
        LazyColumn{
            items(10){ num->
                Text(text = num.toString())
            }
        }
    },
    buttons = {
        Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.End) {
            Button(onClick = { /*TODO*/ }) {
                Text(text = "Cancel")
            }
            Button(onClick = { /*TODO*/ }) {
                Text(text = "Confirm")
            }
        }
    }
)

This won't work

Dialog(onDismissRequest = { /*TODO*/ }) {
    Column(modifier = Modifier.background(color = MaterialTheme.colors.background)) {
        LazyColumn{
            items(40){ num->
                Text(text = num.toString())
            }
        }
        Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.End) {
            Button(onClick = { /*TODO*/ }) {
                Text(text = "Cancel")
            }
            Button(onClick = { /*TODO*/ }) {
                Text(text = "Confirm")
            }
        }
    }
}

You can set a modifier to your AlertDialog to limit the dialog height. Row of buttons are visible.

AlertDialog(
    onDismissRequest = onDismiss,
    modifier = Modifier.fillMaxHeight(.95f),
    buttons = {
        TextButton(onClick = { /*TODO*/ } ) {
            Text(stringResource(id = android.R.string.ok))
        }
    },
    text = {
        LazyColumn(modifier = Modifier.fillMaxSize()) {
            items(40){ num->
                Text(text = num.toString())
            }
        }
    }
)
Related