简体   繁体   中英

ConstraintLayout doesn't quite work with LazyRow in Jetpack Compose

I want to constrain the height of an Image to the height of a LazyRow and align each in a row next to each other. I was able to mostly achieve this layout with this code:

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")
        }
    }
}

But I have a small problem. The LazyRow cuts off the last element:

例子

This problem appears despite using width = Dimension.fillToConstraints and chains. This is the repo if you want to clone

Set your ConstraintLayout to be max width, and add an end constraint to your 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
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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