我希望使用百分比在父视图中定位视图,类似于CSS中的绝对定位。在我的场景中,我将有一个可变且不可预测的视图数量,这将以这种方式定位。
这是一个示例,它表示一个正方形内的3个TextView,其中包含以下位置:
1:前55%,左下29% 2:前77%,左58% 3:前54%,左43%
这是使用自定义绘图最好的完成吗?或者,在给定这些百分比的情况下,是否可以在特定类型的父视图中动态定位视图?如果是前者,我该如何处理文字?如果是后者,父母应该采用什么类型的观点,我应该如何设定这些百分比?
答案 0 :(得分:4)
您可以使用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>
只需确保子视图(Textview)被限制在顶部和底部,这样您就可以设置垂直偏差。并且也可以开始,结束以便设置水平偏差。
结果如下:
这也可以通过编程方式完成,请看这里有一个很好的指南: http://www.zoftino.com/adding-views-&-constraints-to-android-constraint-layout-programmatically
答案 1 :(得分:-2)