如何将一个元素的一侧居中到另一个元素的中间?



我正在使用constraintlayout,并希望将元素的左侧置于其上方的元素的中间。

[I'm Element 1]
        | // middle of element 1
        [Element 2 should start at middle of element 1]

这是不用编写代码而可能的,如果是,如何?

您可以使用约束来对齐元素2。要中心元素,您可以将左侧限制在元素1的左侧,并在右侧进行相同的操作。因此,在XML中,它会像:

<Element2
    android:id="@+id/element2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="@+id/element1"
    app:layout_constraintRight_toRightOf="@+id/element1" />

应该水平居中。如果您也想垂直核心添加顶部和底部约束。

编辑:误解了这个问题,如果要将元素的左侧对齐到另一个元素的中心,则可以使用GuideLine

创建一个指南和位置,它的基准是元素的基线1:

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBaseline_toBaselineOf="@+id/element1"/>

然后将元素的左侧对准指南

<Element2
    android:id="@+id/element2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="@+id/guideline" />

解决方案是以下内容:而不是指南,而是使用1PX * 1PX View作为指南,将其定位在element1的中心,并使用layout_constraintLeft_toLeftOf&amp;layout_constraintRight_toRightOf属性,然后将element2与此View指南对齐:

<android.support.constraint.ConstraintLayout>
    ...
    <TextView
            android:id="@+id/element1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    <View
            android:id="@+id/guideline"
            android:layout_width="1px"
            android:layout_height="1px"
            android:background="#00000000"
            app:layout_constraintLeft_toLeftOf="@id/element1"
            app:layout_constraintRight_toRightOf="@id/element1" />
    <TextView
            android:id="@+id/element2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toRightOf="@id/guideline"
            app:layout_constraintTop_toBottomOf="@id/element1" />
    ...
</android.support.constraint.ConstraintLayout>

相关内容

最新更新