无法在约束布局中居中按钮

时间:2021-05-02 11:03:11

标签: android xml android-layout constraints android-constraintlayout

这个问题可能已经被问了一百万次,看起来微不足道,但在阅读了大约 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>

根据我的理解,如果我设置了相反的约束,渲染引擎会自动将它们解释为百分比……我是说对吗? 如果没有设置特定的边距或任何东西,那么它会拉平距离。这显然意味着按钮应该在视图内居中。但它没有....

enter image description here

我不明白。我想在不设置边距的情况下居中,因为根据我的理解,边距是独立于约束的东西。它在约束内工作。但尽管如此,我还是将每边的边距设置为 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%”之类的内容,这基本上又是中间。当然,这又是行不通的。引擎将其解释为绝对值,按钮处于另一个尴尬的位置:

enter image description here

那怎么办??

我不想做的事: 使用某种指南或偏差对其进行调整。

我想要简单的东西。 只有 4 个约束(xml 中的 4 行)和一个位于任何设备屏幕中间的按钮。

也许有人可以分享一些见解?

1 个答案:

答案 0 :(得分:1)

你应该删除这两个属性:

app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintVertical_bias="0.0"

如您所见,official reference,默认偏差为五十五十 (50% = 0.5)。

<块引用>

例如以下将使左侧有 30% 的偏差 而不是默认的 50%,这样左边会更短, 小部件更倾向于左侧(图 5):