Jetpack Compose 的约束布局ConstraintLayout

1.Android虽然支持约束布局,但是我们还是推荐使用约束盒子布局,嵌套虽然增多,但是代码量整体减少。

2.约束布局还是更适合xml的布局方式,可以有效的减少嵌套,提高性能。但是compose使用ConstraintLayout并不会提高性能。

我们今天实现一个普通的列表中的Item效果

分析布局:

1.整体包裹的父布局是 左右铺满 上下包裹。

2.左侧图片 顶部为父布局顶部 左侧为父布局左侧,边距我们可以使用padding解决。

3.title的位置为:顶部为图片的顶部,左侧为图片的右侧。

4.状态位置为:右侧为父布局右侧,顶部为父布局顶部。

解决:

1.需要使用ConstraintLayout嵌套全部ui


定位子元素:

通过解构声明 分别声明出几个元素的id

```val (img_header, tv_name, tv_content, tv_date, tv_status) = createRefs()```


上图的意思是 声明一个image,他的id为img_header,他对应的位置为" top.linkTo(parent.top) " 翻译成人话是:顶部为父布局的顶部。

同理 title的位置为


如此罗列即可

全部代码为:

```@ExperimentalComposeUiApi

@Composable

fun ConstraintLayoutItem(item: Int) {

ConstraintLayout(

modifier = Modifier

.padding(top = 5.dp, bottom = 5.dp)

.clickable { }

            .fillMaxWidth()

.clip(RoundedCornerShape(5.dp))

.background(color = Color.White)

.padding(10.dp)

.wrapContentHeight()

//            .border(border = BorderStroke(width = 1.dp, color = Color.Green), shape = RoundedCornerShape(5.dp))

    ){

        val (img_header, tv_name, tv_content, tv_date, tv_status) = createRefs()

Image(

painter = painterResource(id = R.mipmap.dog),

            contentDescription = null,

            contentScale = ContentScale.FillBounds,

            modifier = Modifier

.constrainAs(img_header){

                    top.linkTo(parent.top)

start.linkTo(parent.start)

}

                .height(80.dp)

.width(80.dp)

.clip(shape = RoundedCornerShape(50))

)

Text(text = "周杰伦${item}", modifier = Modifier

.constrainAs(tv_name){

                top.linkTo(img_header.top)

start.linkTo(img_header.end)

}

            .padding(start = 10.dp),

            fontWeight = FontWeight.Bold,

            fontSize = 18.sp)

Text(

text = "今天发新专辑啦",

            modifier = Modifier

.constrainAs(tv_content){

                    top.linkTo(tv_name.bottom)

start.linkTo(img_header.end)

}

                .padding(start = 10.dp, top = 10.dp), style = TextStyle(color = Color.Gray))

Text(

text = "2022年01月24日11:55:51", modifier = Modifier

.constrainAs(tv_date){

                    top.linkTo(tv_content.bottom)

start.linkTo(tv_content.start)

}

                .padding(start = 10.dp, top = 10.dp), style = TextStyle(color = Color.LightGray)

)

Text(

text = "已发行", modifier = Modifier.constrainAs(tv_status){

                top.linkTo(tv_name.top)

end.linkTo(parent.end)

}, color = Color.Blue, fontWeight = FontWeight.Bold

        )

}

}```

你可能感兴趣的:(Jetpack Compose 的约束布局ConstraintLayout)