在ConstraintLayout中有一个具有相同宽度和高度的ImageView

问题描述 投票:0回答:2

如何让ImageView的宽度和高度等于父ConstraintLayout的宽度?所以它显示了一个全宽的方形 ImageView。

通常如何将某个小部件的高度设置为等于其他小部件的宽度?

imageview android-imageview android-constraintlayout
2个回答
11
投票

以下布局将在父级

ConstraintLayout
的中心放置一个方形蓝色图像。关键是
app:layout_constraintDimensionRatio="1:1"
。有关详细信息,请参阅文档

您还可以将小部件的一个尺寸定义为另一个尺寸的比率。为此,您需要至少将一个约束尺寸设置为 0dp(即 MATCH_CONSTRAINT),并将属性layout_constraintDimensionRatio 设置为给定比率。

<android.support.constraint.ConstraintLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/holo_blue_light"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

0
投票

@Cheticamp 的回答很棒。这是 AndroidX 的答案。

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:androidx="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@android:color/holo_blue_light"
            androidx:layout_constraintBottom_toBottomOf="parent"
            androidx:layout_constraintDimensionRatio="1:1"
            androidx:layout_constraintLeft_toLeftOf="parent"
            androidx:layout_constraintRight_toRightOf="parent"
            androidx:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
© www.soinside.com 2019 - 2024. All rights reserved.