5

我正在尝试使用 LazyVerticalGrid 显示分页项目。我正在尝试的代码如下所示。

 val categories = repo.categories.collectAsLazyPagingItems()

 LazyVerticalGrid(
    cells = GridCells.Fixed(2),
    modifier = Modifier.padding(8.dp)
 ) {

      items(categories) { category ->
          Box(Modifier.padding(8.dp)) {
              CategoryView(category)
          }
      }

 }

请注意,我已导入androidx.paging.compose.itemsandroidx.paging.compose.collectAsLazyPagingItems. 也是categories类型LazyPagingItems<Category>

它与LazyColumnandLazyRow但不是完美配合LazyVerticalGrid。我得到的错误是:

Type mismatch.
Required:
Int
Found:
LazyPagingItems<Category>
4

1 回答 1

9

我想出了一个解决方案,方法是LazyGridScope为库LazyListScope中编写的扩展函数编写一个扩展函数androidx.paging:paging-compose

@ExperimentalFoundationApi
public fun <T: Any> LazyGridScope.items(
    lazyPagingItems: LazyPagingItems<T>,
    itemContent: @Composable LazyItemScope.(value: T?) -> Unit
) {
    items(lazyPagingItems.itemCount) { index ->
        itemContent(lazyPagingItems[index])
    }
}
于 2021-07-20T12:23:40.600 回答