使用场景
在Android中,如果想让组件和父组件的宽高保持一致,使用match_parent
即可。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Match Parent Text"
android:textSize="30sp"
android:textColor="@color/black"/>
</LinearLayout>
在Compose
中,Row
和Column
扮演了linearLayout
的角色。但是他们的Modifier
中没有这个属性.
解决方案
在Compose
中要达到match_parent
的效果,需要使用height(IntrinsicSize.Min)
配合fillMaxHeight()
才行。
在Row
中使用height(IntrinsicSize.Min)
,然后所有子组件设置fillMaxHeight()
布局将按最大子组件的高度作为父组件的高度,同时其它子组件也会保持一样的高度.
在Column
中同时,使用width(IntrinsicSize.Min)
和fillMaxWidth()
示例
@Composable
private fun RowDemo() {
Row(
modifier = Modifier.height(IntrinsicSize.Min),
) {
Box(
modifier = Modifier
.background(Color.Cyan)
.fillMaxHeight()
.weight(1F),
) {
Column {
Text("我是最大高度的子组件")
Box(Modifier.height(200.dp))
}
}
Box(
modifier = Modifier
.fillMaxHeight()
.background(Color.Red)
.weight(1F),
) {
Text("我是一行文字,但是我也和父组件一样的高度")
}
Text(
modifier = Modifier
.fillMaxHeight()
.background(Color.Green)
.weight(1F),
text = "我是一行文字,但是我也和父组件一样的高度,并且水平剧中显示",
textAlign = TextAlign.Center,
maxLines = 1,
)
}
}