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"
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章