Android ConstraintLayout 设置子 view maxWidth 是父 ConstraintLayout width 的百分比

话不多说,直接上代码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
    	android:background="@color/colorPrimary"
        app:layout_constraintWidth_max="wrap"
        app:layout_constraintWidth_percent="0.1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Hello World Hello World Hello World Hello World"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

关键就是:

app:layout_constraintWidth_max="wrap"  <!-- 设置为 wrap -->
app:layout_constraintWidth_percent="0.1"  <!-- 设置为想要的比例 -->
android:layout_width="0dp"  <!-- 注意是 0dp -->

但是有一点需要注意,如果此时 view 没有填充内容,比如 TextView 没有 text,此时其 width 就会被直接设置 percent 对应的宽度。 比如上述示例代码,TextView 的 text 设置为 "" 空字符串,或者 null,其 width 就会被设置为 ConstraintLayout width 的 0.1

下面 percent="0.1"
在这里插入图片描述
下面 percent="0.5"
在这里插入图片描述

补充

1、对于上述场景,如果是动态去设置 TextView 的内容,且宽度随内容的而变化,且满足

app:layout_constraintWidth_max="wrap"
app:layout_constraintWidth_percent="0.1"

即最大宽度为父布局的 0.1,则在动态设置内容之后,需要调用 TextView#requestLayout(),来使得布局在因内容长度变化导致宽度变化之后刷新布局。

如果没有 requestLayout(),则当对 TextView 设置了很长的内容导致其宽度变宽之后(假设变宽之后为 W),再设置较短内容时,宽度还是会维持为 W,不会实时的因为内容变短而变短。

2、如果子 View 是自定义的,则需要处理这种 wrap 情况,因为我们设置的子 view 的 android:layout_width 为 0

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值