我们如何将ImageView的宽度和高度设置为父级ConstraintLayout的宽度?这样就可以显示一个完整的宽度为正方形的ImageView。
通常情况下,我们如何将某个小部件的高度设置为另一个小部件的宽度?
通常情况下,我们如何将某个小部件的高度设置为另一个小部件的宽度?
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>
<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>