首页 > 解决方案 > ConstraintLayout 不太适用于 Jetpack Compose 中的 LazyRow

问题描述

我想将 a 的高度限制Image为 a 的高度,LazyRow并将每一个彼此相邻对齐。我可以用这段代码实现这个布局:

package com.example.test

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.ConstraintLayout
import androidx.compose.foundation.layout.Dimension
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.unit.dp



@Composable
fun Test() {
    ConstraintLayout {
        val (image, row) = createRefs()
        createVerticalChain(image, row)
        ARow(modifier = Modifier.constrainAs(row) {
            start.linkTo(image.end)
            width = Dimension.fillToConstraints
        })

        AImage(modifier = Modifier.constrainAs(image) {
            top.linkTo(row.top)
            bottom.linkTo(row.bottom)
            height = Dimension.fillToConstraints
        })
    }
}


@Composable
fun AImage(modifier: Modifier = Modifier) {
    Image(
        modifier = modifier,
        bitmap = imageResource(id = R.drawable.sample_ic),
        )
}

@Composable
fun ARow(modifier: Modifier = Modifier) {
    LazyRow(modifier = modifier) {
        items((0..10).toList()) {
            Text(modifier = Modifier.padding(8.dp), text = "Item: $it")
        }
    }
}

但我有一个小问题。LazyRow切断最后一个元素:

例子

尽管使用了width = Dimension.fillToConstraints和链,但仍会出现此问题。如果你想克隆,这是 repo

标签: androidandroid-jetpack-compose

解决方案


将您设置ConstraintLayout为最大宽度,并为您添加一个结束约束ARow

ConstraintLayout(modifier = Modifier.fillMaxWidth()) {
    val (image, row) = createRefs()
    createVerticalChain(image, row)
    ARow(modifier = Modifier.constrainAs(row) {
        start.linkTo(image.end)
        end.linkTo(parent.end)
        width = Dimension.fillToConstraints
    })

    AImage(modifier = Modifier.constrainAs(image) {
        top.linkTo(row.top)
        bottom.linkTo(row.bottom)
        height = Dimension.fillToConstraints
    })
}

推荐阅读