Jetpack Compose. How to center text in LazyColumn

290 Views Asked by At

I'm trying to implement simple list. When list is empty I need to show empty placeholder in the center of the screen. Here is my code:

 LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues),
        ) {
            if (itemList.isEmpty()) {
                item {
                    Box(
                        modifier = Modifier.fillMaxSize().padding(20.dp),
                        contentAlignment = Alignment.Center,
                    ) {
                        Text(
                            textAlign = TextAlign.Center,
                            text = stringResource(id = R.string.empty_text),
                        )
                    }
                }
            } else {
                items(itemList) { item ->
                    Item(
                        modifier = Modifier.fillMaxWidth(),
                        item = item,
                        onItemClick = onItemClick,
                    )
                }
            }
        }

But the problem is that the text is not located in the center but on top, how to fix this? Please help me.

1

There are 1 best solutions below

0
On

Use a Box as a parent, and then put your lazy column and placeholder inside of it. Show the placeholder if the list is empty. Align the content of the box as center:

   Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .padding(paddingValues),
    ) {
        items(itemList) { item ->
            Item(
                modifier = Modifier.fillMaxWidth(),
                item = item,
                onItemClick = onItemClick,
            )
        }
    }
    if (itemList.isEmpty()) {
        Box(
            modifier = Modifier.fillMaxSize().padding(20.dp),
            contentAlignment = Alignment.Center,
        ) {
            Text(
                textAlign = TextAlign.Center,
                text = stringResource(id = R.string.empty_text),
            )
        }

    }
}