AndroidCompose:使用动态GridItemSpan的LazyVerticalGridDSL,是否有spanSizeLookup?
创始人
2024-10-06 20:30:45
0

目前,Compose的LazyVerticalGrid DSL不支持设置spanSizeLookup。 但是,仍然可以通过编写自定义LazyItemScope并在其中使用LayoutInfo提供所需的功能。 下面是一个包含代码示例的解决方案:

@Composable
fun  LazyVerticalGridWithDynamicSpan(
    items: List,
    spanCount: Int = 2,
    itemContent: @Composable LazyItemScope.(T) -> Unit
) {
    val lazyListState = rememberLazyListState()
    val layoutInfo = remember {
        GridLayoutInfo(
            spanCount = spanCount,
        )
    }
  
    LazyVerticalGrid(
        cells = GridCells.Adaptive(minSize = 128.dp),
        state = lazyListState,
        layoutInfo = layoutInfo,
        contentPadding = PaddingValues(8.dp)
    ) {
        items(items = items) { item ->
            DynamicSpanLazyItemScope(layoutInfo) {
                itemContent(item)
            }
        }
    }
}

// 自定义LazyItemScope,用于获取当前item所占的GridItemSpan
internal class DynamicSpanLazyItemScope(
    private val layoutInfo: GridLayoutInfo,
    content: @Composable LazyItemScope.() -> Unit
) : LazyItemScope {

    private var span: Int? = null
  
    init {
        content()
        span = span ?: layoutInfo.spanCount // 如果没有设置span,则一个item占一个GridItemSpan
    }
  
    override fun Modifier.requiredWidth(): IntPx {
        return layoutInfo.cellSize * span!! + layoutInfo.horizontalGap * (span!! - 1)
    }

    override fun Modifier.requiredHeightForWidth(width: IntPx): IntPx {
        return layoutInfo.getIntrinsicHeightForWidth(width) * span!!
    }

    override fun MeasureScope.measure(
        measurable: Measurable,
        constraints: Constraints,
        layoutDirection: LayoutDirection
    ): MeasureResult {
        val itemConstraints = Constraints(
            minWidth = layoutInfo.cellSize * span!!,
            maxWidth = layoutInfo.cellSize * span!!,
            minHeight = layoutInfo.getIntrinsicHeightForWidth(constraints.maxWidth) * span!!,

相关内容

热门资讯

记者揭秘!wepoker线上大... 记者揭秘!wepoker线上大神,wpk辅助购买,揭秘攻略(有挂辅助)1、不需要AI权限,帮助你快速...
今日头条!德州局hhpoker... 您好,德州局hhpoker这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩...
教程辅助!pokermaste... 1、教程辅助!pokermaster辅助器,德州透视是真的吗,2025新版技巧(有挂教程)。2、德州...
重大通报!wepoker怎么挂... 重大通报!wepoker怎么挂飞机,wepoker有没有机器人,2025新版技巧(有挂透明)1、玩家...
总算了解!htx矩阵wepok... 1、总算了解!htx矩阵wepoker辅助,epoker透视底牌,必胜教程(有挂辅助);详细教程。2...
发现玩家!hhpoker有没有... 发现玩家!hhpoker有没有作弊挂,agpoker辅助,大神讲解(有挂神器);支持2-10人实时对...
发现玩家!扑克之星辅助,pok... 发现玩家!扑克之星辅助,pokemmo手机脚本,AI教程(有挂辅助);建议优先通过pokemmo手机...
重大来袭!德州局脚本,wpk辅... 重大来袭!德州局脚本,wpk辅助,辅助教程(有挂技巧);1.德州局脚本 ai辅助创建新账号,点击进入...
玩家必备攻略!hhpoker怎... 玩家必备攻略!hhpoker怎么开透视,pokerworld破解版下载,新版2025教程(有挂技巧)...
实测发现!xpoker怎么作弊... 实测发现!xpoker怎么作弊,wepoker数据分析工具,详细教程(有挂方法);原来确实真的有挂(...