【发布时间】:2021-07-25 01:51:52
【问题描述】:
这个问题可能已经被问了一百万次并且看起来微不足道,但在阅读了大约 100 个答案后,我仍然不明白其背后的逻辑。
我有这个超简单的 XML 布局
<?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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
根据我的理解,如果我设置了相反的约束,渲染引擎会自动将它们解释为百分比......我的意思是对吗? 如果没有设置特定的边距或任何东西,那么它会平衡距离。这显然意味着按钮应该位于视图内的中心位置。但它没有....
我不明白。我想以不设置边距为中心,因为据我所知,边距是独立于约束的东西。它在约束内工作。但尽管如此,我还是在每边设置了 50 的边距。一旦在相对两侧设置了边距,引擎应该自动将其渲染为百分比......对吗?
所以这个 XML:
<?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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="50dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
应该说“约束是左上右下的 50%”,这基本上又是中间。当然,这又是行不通的。引擎将其解释为绝对值,按钮处于另一个尴尬的位置:
那该怎么做呢??
我不想做的事: 使用某种指南或偏差对其进行调整。
我想要简单的东西。 只有 4 个约束(xml 中的 4 行)和一个位于任何设备屏幕中间的按钮。
也许有人可以分享一些见解?
【问题讨论】:
-
如果你不想用bias调整它,你为什么要添加bias?当你尝试调试这样的事情时,你应该创建一个minimal reproducible example,它(如果做得正确)会在你提出问题之前向你展示解决方案。
标签: android xml android-layout constraints android-constraintlayout