水平链中的两个视图,当一个是View.GONE时,另一个应在父视图中居中

问题描述

constraintLayout水平链中有两个彼此相邻的视图。

但是,当其中一个视图是View.GONE(以编程方式设置)时,我希望另一个视图在其父视图内居中。我已经尝试过水平链接,但是似乎没有用。

即我要从这里开始:

enter image description here

对此:

enter image description here

但是,当我将按钮2设置为View.GONE时,按钮1停留在同一位置,稍微向左倾斜,就好像按钮2是View.INVISIBLE而不是View.GONE一样。

    <Button
        android:id="@+id/btn_1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/btn_2"
        app:layout_constraintTop_toBottomOf="parent" />

    <Button
        android:id="@+id/btn_2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintLeft_toRightOf="@id/btn_1"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="parent" />

解决方法

尝试一下:

<Button
    android:id="@+id/btn_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    app:layout_constraintHorizontal_weight="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@id/btn_2"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btn_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    app:layout_constraintHorizontal_weight="1"
    app:layout_constraintLeft_toRightOf="@id/btn_4"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
,

结果是我有一个ConstraintLayout组,该组引用了两个干扰链接的按钮。一旦我删除了该小组,一切都会按预期进行。