【问题标题】:How to position views using percentage for top/left within container?如何使用容器内顶部/左侧的百分比来定位视图?
【发布时间】:2018-07-26 23:56:16
【问题描述】:

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

这是一个例子,它代表了一个正方形内的 3 个 TextView,位置如下:

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

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

【问题讨论】:

  • 你想通过 x y 位置设置文本?
  • @HemantParmar 是的
  • 好的,然后使用绝对布局。
  • @HemantParmar 感谢您的提示 - 如果这是正确的方法,我会感谢答案中的示例和说明,供我自己和其他任何遇到此答案的人使用。
  • 我发布了答案和示例,看看,可能对你有帮助。谢谢!!

标签: android android-layout position android-view


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:

    根据X&Y位置设置视图,使用Android绝对布局这里是Example

    希望对你有帮助!!

    【讨论】:

    • 看起来 AbsoluteLayout 已被弃用。有其他选择吗?
    • 它在我的所有版本上运行。我检查其他替代方案。
    • 是的,它似乎仍然可以工作,但 Android Studio 显示它已被弃用。
    • 我得到了this 替代方案可能对您有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    相关资源
    最近更新 更多