Olu*_*deh 18 android android-jetpack-compose android-paging-3
我正在尝试使用 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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我已经导入了androidx.paging.compose.items和androidx.paging.compose.collectAsLazyPagingItems。也categories属于类型LazyPagingItems<Category>。
LazyColumn它可以与和完美配合LazyRow,但不能LazyVerticalGrid。我收到的错误是:
Type mismatch.
Required:
Int
Found:
LazyPagingItems<Category>
Run Code Online (Sandbox Code Playgroud)
Olu*_*deh 21
我想出了一个解决方案,为库中LazyGridScope编写的函数编写一个扩展函数。LazyListScopeandroidx.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])
}
}
Run Code Online (Sandbox Code Playgroud)
对我来说,接受的答案不起作用。我没有添加扩展功能,而是使用了以下方式
val res = viewModel.getFeedResultStream().collectAsLazyPagingItems()
LazyVerticalGrid(columns = GridCells.Fixed(2)){
items(res.itemCount)
{ index ->
res[index]?.let {
FeedItem(it)
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
从 androidx.paging:paging-compose 复制
fun <T : Any> LazyGridScope.items(
items: LazyPagingItems<T>,
key: ((item: T) -> Any)? = null,
itemContent: @Composable LazyGridItemScope.(item: T?) -> Unit
) {
items(
count = items.itemCount,
key = if (key == null) null else { index ->
val item = items.peek(index)
if (item == null) {
PagingPlaceholderKey(index)
} else {
key(item)
}
}
) { index ->
itemContent(items[index])
}
}
@SuppressLint("BanParcelableUsage")
private data class PagingPlaceholderKey(private val index: Int) : Parcelable {
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(index)
}
override fun describeContents(): Int {
return 0
}
companion object {
@Suppress("unused")
@JvmField
val CREATOR: Parcelable.Creator<PagingPlaceholderKey> =
object : Parcelable.Creator<PagingPlaceholderKey> {
override fun createFromParcel(parcel: Parcel) =
PagingPlaceholderKey(parcel.readInt())
override fun newArray(size: Int) = arrayOfNulls<PagingPlaceholderKey?>(size)
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
无需创建扩展函数。只需使用其他版本的items功能即可。
val categories = repo.categories.collectAsLazyPagingItems()
LazyVerticalGrid(
cells = GridCells.Fixed(2),
modifier = Modifier.padding(8.dp)
) {
items(
categories.itemCount
) { index ->
Box(Modifier.padding(8.dp)) {
CategoryView(categories[index])
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8283 次 |
| 最近记录: |