繁体   English   中英

如何将一个元素的侧面居中放置在另一个元素的中间?

[英]How can I center an element's side to middle of an other element?

我正在使用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

创建一个准则并将其基线定位到Element1的基线:

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

然后将element2的左侧与GuideLine对齐

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

解决方案如下:使用1px * 1px View作为参考线,而不是参考线,使用layout_constraintLeft_toLeftOflayout_constraintRight_toRightOf属性将其定位到element1的中心,然后将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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM