0

我正在尝试使用 Compose 实现 2 列的网格布局,但 LazyVertical Grid 对我不起作用。我搜索了一些解决方法来完成任务,但屏幕上没有呈现任何内容。有任何想法吗?

 val state = rememberLazyListState()
    LazyVerticalGrid(
        cells = GridCells.Fixed(2),
        state = state,
        content = {
            items(bookList.books){
                bookList.books.map {
                    BookUI(book = it, onClick = {})
                }
            }
        }
    ) 

我尝试以这种方式使用 LazyVerticalGrid,但它不呈现列表,而 LazyColumn 呈现它

4

2 回答 2

1

map使用时不需要 a items

改变

items(bookList.books){
    bookList.books.map {
        BookUI(book = it, onClick = {})
    }
}

items(bookList.books){ book ->
    BookUI(book = it, onClick = {})        
}

别忘了导入,

import androidx.compose.foundation.lazy.items
于 2022-02-15T13:49:42.563 回答
0

尝试使用以下代码:

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun MyGrid(items: List<String>) {
    LazyVerticalGrid(
        cells = GridCells.Fixed(count = 2)
    ) {
        items(items) { text ->
            Text(text = text)
        }
    }
}

您应该注意的几件事:

  • items(*) {}功能需要从androidx.compose.foundation.lazy.items

  • 你添加了@OptIn(ExperimentalFoundationApi::class)

  • rememberLazyListState()实际上是一个默认参数,所以不需要添加它。

对于上面的示例,您可以使用以下内容:

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Content() {
    MyGrid(
        items = listOf(
            "Item A",
            "Item B",
            "Item C",
            "Item D",
            "Item E",
            "Item F"
        )
    )
}

你会得到这个:

例子

于 2022-02-15T20:32:54.563 回答