首页 > 解决方案 > 如何使用 layout_constraintWidth_percent 使视图成为屏幕的 1/3?

问题描述

这是我的自定义视图,我的自定义视图的宽度与 ImageView 的宽度一样多,我将 ImageView 宽度设置为屏幕宽度的 1/3,maxWidth 应为 140dp 但它不起作用

这是我的 xml 文件,问题是忽略了我所描述的百分比 android:maxWidth="144dp" app:layout_constraintWidth_default="percent" app:layout_constraintWidth_percent=".3"

我有 layout_width 和 layout_height 一样多的空间
android:layout_width="40dp" android:layout_height="40dp"

<?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:id="@+id/home_card_root_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:duplicateParentState="true"
        android:ellipsize="end"
        android:gravity="start"
        android:maxLines="2"
        app:layout_constraintBottom_toTopOf="@+id/subtitle"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/image"
        tools:text="Title"
        tools:textColor="#000000"
        tools:visibility="visible" />

    <TextView
        android:id="@id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:drawablePadding="4dp"
        android:duplicateParentState="true"
        android:ellipsize="end"
        android:gravity="start"
        tools:text="Sub Title"
        android:maxLines="1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title" />

    <ImageView
        android:id="@+id/image"
        tools:ignore="SpContentDescription"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:maxWidth="144dp"
        app:layout_constraintWidth_default="percent"
        app:layout_constraintWidth_percent=".3"
        android:layout_marginBottom="8dp"
        android:duplicateParentState="true"
        android:background="@color/gray_70"
        android:scaleType="centerCrop"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintBottom_toTopOf="@+id/title"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:background="@drawable/ic_launcher_background" />

</androidx.constraintlayout.widget.ConstraintLayout>

https://i.stack.imgur.com/rLu1Q.png

标签: androidandroid-layoutandroid-constraintlayout

解决方案


推荐阅读