[Compose]子组件匹配Row和Column的宽高达到Android中xml的match_parent效果

使用场景

在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中,RowColumn扮演了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,
        )
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值