【问题标题】:ConstraintLayout doesn't quite work with LazyRow in Jetpack ComposeConstraintLayout 不太适用于 Jetpack Compose 中的 LazyRow
【发布时间】:2021-01-14 15:09:18
【问题描述】:

我想将Image 的高度限制为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 和链,仍会出现此问题。 This 是你想要克隆的仓库

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    将您的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
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2022-09-26
      • 1970-01-01
      • 2021-06-29
      • 2022-11-08
      • 2022-11-10
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多