1.Android雖然支持約束布局,但是我們還是推薦使用約束盒子布局笋庄,嵌套雖然增多,但是代碼量整體減少倔监。
2.約束布局還是更適合xml的布局方式直砂,可以有效的減少嵌套,提高性能浩习。但是compose使用ConstraintLayout并不會提高性能静暂。
我們今天實現(xiàn)一個普通的列表中的Item效果
分析布局:
1.整體包裹的父布局是 左右鋪滿 上下包裹。
2.左側(cè)圖片 頂部為父布局頂部 左側(cè)為父布局左側(cè)瘦锹,邊距我們可以使用padding解決籍嘹。
3.title的位置為:頂部為圖片的頂部,左側(cè)為圖片的右側(cè)弯院。
4.狀態(tài)位置為:右側(cè)為父布局右側(cè)辱士,頂部為父布局頂部。
解決:
1.需要使用ConstraintLayout嵌套全部ui
定位子元素:
通過解構(gòu)聲明 分別聲明出幾個元素的id
```val (img_header, tv_name, tv_content, tv_date, tv_status) = createRefs()```
上圖的意思是 聲明一個image听绳,他的id為img_header颂碘,他對應(yīng)的位置為"?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 = "今天發(fā)新專輯啦",
? ? ? ? ? ? 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 = "已發(fā)行", modifier = Modifier.constrainAs(tv_status){
? ? ? ? ? ? ? ? top.linkTo(tv_name.top)
end.linkTo(parent.end)
}, color = Color.Blue, fontWeight = FontWeight.Bold
? ? ? ? )
}
}```