如何在容器内使用 top/left 的百分比定位视图?
How to position views using percentage for top/left within container?
我希望使用百分比在父视图中定位视图,类似于 CSS 中的绝对定位。在我的场景中,我将以这种方式放置数量可变且不可预测的视图。
这是一个示例,它代表一个正方形内的 3 个 TextView,其位置如下:
1:前 55%,左 29%
2: 前 77%, 左 58%
3: 前54%, 左43%
这是否最好使用自定义绘图来完成?或者是否可以在给定这些百分比的情况下在某种类型的父视图中动态定位视图?如果是前者,我该如何处理文本?如果是后者,父级应该是什么类型的视图,我应该如何设置这些百分比?
根据X&Y位置设置视图,使用Android绝对布局这里是Example
希望对您有所帮助!!
你可以使用 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
我希望使用百分比在父视图中定位视图,类似于 CSS 中的绝对定位。在我的场景中,我将以这种方式放置数量可变且不可预测的视图。
这是一个示例,它代表一个正方形内的 3 个 TextView,其位置如下:
1:前 55%,左 29%
2: 前 77%, 左 58%
3: 前54%, 左43%
这是否最好使用自定义绘图来完成?或者是否可以在给定这些百分比的情况下在某种类型的父视图中动态定位视图?如果是前者,我该如何处理文本?如果是后者,父级应该是什么类型的视图,我应该如何设置这些百分比?
根据X&Y位置设置视图,使用Android绝对布局这里是Example
希望对您有所帮助!!
你可以使用 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