据我所知,如果我在元素中使用
app:layout_constraintDimensionRatio="H,1:1
,该元素的高度将被固定,然后宽度将适应与宽度相同的大小,但在下面的示例中,高度不固定。
这是代码:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/gd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.1" />
<View
android:id="@+id/v1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toTopOf="@id/gd"
app:layout_constraintDimensionRatio="H,1:1"
android:background="@color/blue"
app:layout_constraintHorizontal_bias="1.0"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
我预期会发生什么:
到底发生了什么:
奇怪的事实
如果我在我拥有的视图旁边添加具有相同
app:layout_constraintDimensionRatio="H,1:1"
的另一个视图(形成两个视图的水平链),app:layout_constraintDimensionRatio="H,1:1"
现在会按预期神秘地工作。
现在有两个视图的代码:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/gd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.1" />
<View
android:id="@+id/v1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintEnd_toStartOf="@id/v2"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toTopOf="@id/gd"
app:layout_constraintDimensionRatio="H,1:1"
android:background="@color/blue"
/>
<View
android:id="@+id/v2"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="@id/v1"
app:layout_constraintBottom_toTopOf="@id/gd"
app:layout_constraintDimensionRatio="H,1:1"
android:background="@color/blue"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
预期以及实际发生的情况:
现在我的问题是,为什么如果我有一个视图
app:layout_constraintDimensionRatio="H,1:1"
无法按预期工作,但如果我添加第二个视图与第一个视图形成水平链app:layout_constraintDimensionRatio="H,1:1"
现在可以工作?
app:layout_constraintDimensionRatio="H,1:1"
表示H8 应在设置Width 之后遵循该纵横比。
在您的示例中,您已将两端的 Start 和 End 设置为父级。所以宽度应该是数学父项。现在高度将与宽度一样大。在第二个示例中,您限制了其宽度。
H八将尊重该比例。
尝试将第一个示例中的H
更改为
W
,看看会发生什么。 (您限制的是高度而不是宽度)