如何使用容器中顶部/左侧的百分比来定位视图?

Jak*_*ake 5 android position android-layout android-view

我希望使用百分比在父视图中定位视图,类似于CSS中的绝对定位.在我的场景中,我将有一个变量和不可预测的视图数量将以这种方式定位.

下面是一个示例,它表示一个正方形内的3个TextView,其中包含以下位置:

1:前55%,左29%
2:前77%,左58%
3:前54%,左43%

有百分比头寸的观点

这是使用自定义绘图最好的完成吗?或者,在给定这些百分比的情况下,是否可以在特定类型的父视图中动态定位视图?如果是前者,我该如何处理文字?如果是后者,父母应该采用什么类型的观点,我应该如何设定这些百分比呢?

Eoi*_*oin 7

您可以使用ConstraintLayout https://developer.android.com/training/constraint-layout/index.html

约束布局可让您根据需要使用水平和垂直偏差的百分比来放置视图。例如:

<android.support.constraint.ConstraintLayout
    android:id="@+id/constraint"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <TextView
        android:id="@+id/edition_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.33"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.33"
        android:background="@android:color/holo_purple"
        android:text="text"/>

</android.support.constraint.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

只需确保子视图(文本视图)限制在顶部和底部,即可设置垂直偏向。还要开始,结束,以便您可以设置水平偏差。

结果是这样的:

在此处输入图片说明

而且这也可以通过编程方式完成,请参见此处以获取良好指南:http : //www.zoftino.com/adding-views-&--constraints-to-android-constraint-layout-以编程方式