I have a screen where I need to show a header and a list of items wrapped in a card view. The whole screen has to be scrollable (like shown in the image below).
I know how to do this with a scrollable Column but I want to be able to use a LazyColumn
(because each list item will have its own ViewModel due to the complexity of the view and I thought LazyColumn will be more resources-efficient). For the header, I can use item
and for the list, I can use items
. Below is the code I tried:
@Composable
fun Screen(
items: List<String>
) {
Column(
Modifier.fillMaxSize()
) {
TopAppBar(title = { Text(text = "My Activity") })
LazyColumn {
// Header
item {
Text("Title", Modifier.padding(32.dp))
}
// I cannot use Box in this way here
Box(Modifier.padding(32.dp)) {
Card {
items(items.size) {
Text("Item $it")
}
}
}
}
}
}
The problem with that code is that I cannot wrap the list items in a card view because Card
is not a LazyListScope
. Using LazyColumn, how can I wrap the list items in a Card?
You can define your "Card" as a single item
containing nested items
.
items
being part of LazyListScope
you need to use kotlin explicit this
such as this@LazyColumn
@Composable
fun Screen(
items: List<String>
) {
Column(
Modifier.fillMaxSize()
) {
TopAppBar(title = { Text(text = "My Activity") })
LazyColumn( Modifier.fillMaxSize()) {
// Header
item {
Text("Title", Modifier.padding(32.dp))
}
// Single item
item {
// Your Box list here
Box(Modifier.padding(32.dp)) {
Card {
this@LazyColumn.items(items.size) {
Text("Item $it")
}
}
}
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.