繁体   English   中英

LazyVerticalGrid 用于在 jetpack compose 中分页项目

[英]LazyVerticalGrid for paging items in jetpack compose

我目前正在通过下面的扩展函数在LazyVerticalGrid中使用分页项( LazyPagingItems ),它工作正常。

inline fun <T : Any> LazyGridScope.items(
    items: LazyPagingItems<T>,
    crossinline itemContent: @Composable LazyGridItemScope.(item: T?) -> Unit
) {
    items(count = items.itemCount) { index ->
        itemContent(items[index])
    }
}

但是,我想利用LazyLazyout提供的其他参数,如keyspan等,并尝试以下功能。

inline fun <T : Any> LazyGridScope.items(
    items: LazyPagingItems<T>,
    noinline key: ((item: T?) -> Any)? = null,
    noinline span: (LazyGridItemSpanScope.(item: T?) -> GridItemSpan)? = null,
    noinline contentType: (item: T?) -> Any? = { null },
    crossinline itemContent: @Composable LazyGridItemScope.(item: T?) -> Unit
) = items(
    count = items.itemCount,
    key = if (key != null) { index: Int -> key(items[index]) } else null,
    span = if (span != null) { { span(items[it]) } } else null,
    contentType = { index: Int -> contentType(items[index]) }
) {
    itemContent(items[it])
}

当我将该函数与key一起使用时,它显示错误Type mismatch: inferred type is Long? but Any was expected Type mismatch: inferred type is Long? but Any was expected的。

items(items = products, key = { product -> product?.productId }) {
//Content
}

我想这是由于声明了public class LazyPagingItems<T : Any> 如何解决它以将所有参数与分页项一起使用?

使用product?.productId你试图传递一个可选的Int? 值,而key需要一个非可选的Any值。

当您将key = null传递给计算块时,它会根据索引为每个对象创建一个唯一的键。 特定的项目键不能为null ,因为这会使它等于其他项目键,这是被禁止的。

您可以只为非可选项目设置调用key ,并为可选案例提供index作为默认值:

inline fun <T : Any> LazyGridScope.items(
    // ...
    noinline key: ((item: T) -> Any)? = null,
    // ...
) = items(
    // ...
    key = if (key != null) { index: Int -> items[index]?.let(key) ?: index } else null,
    // ...

用法:

items(items = products, key = { product -> product.productId }) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM