【问题标题】:Centre view in parent and below a certain view在父视图和某个视图下方居中视图
【发布时间】:2018-08-31 04:22:06
【问题描述】:
  1. View A 将在 Parent 中居中
  2. View B (TextView) 将出现在父级的顶部。
  3. 但是随着视图 B 的高度增加并到达视图 A,它应该尽可能地向下推视图 A 以显示其所有内容。

如果我使用相对布局,我可以将视图 A 放到父视图的垂直中心或视图 B 下方。但我无法同时实现这两者。 此外,只有当视图 A 在相对布局中低于视图 B 时,#3 似乎是可能的,但是我不能让它在父视图的中心开始,而视图 B 的高度不足以到达视图 A。

有人可以提供一些建议吗? 谢谢

【问题讨论】:

  • 如果您分享所需输出的任何图像或屏幕截图,那就太好了
  • 使用 ConstraintLayout 并设置约束。这是 PercentRelativeLayout 的更好版本,它让您可以使用百分比并设置相对于彼此的视图,而无需嵌套它们。
  • @Thracian:你能解释一下怎么做吗?
  • @Sunny ConstraintLayout 非常容易学习。按照本教程,您将在 15 分钟内掌握它。 codelabs.developers.google.com/codelabs/constraint-layout/… 要设置约束动态搜索 SO,我还没有在运行时更改任何内容。它还可以更轻松地为视图使用基于位置的动画。使用 2 种布局也很容易将视图从一个位置移动到另一个位置。
  • 你不需要有 ConstraintLayout 的父母,一切都可以定位在屏幕的任何部分或相对于其他视图。

标签: android android-layout android-linearlayout android-constraintlayout


【解决方案1】:

试试这个:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/holo_blue_dark"
    android:text="TextView1" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/holo_green_dark"
    android:text="TextView2"/>

</LinearLayout>

以编程方式将第一个 View 的 minHeight 设置为。

ViewTreeObserver observer = linearLayout.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {

            int height = linearLayout.getHeight(); // set height/2 as minHeight for the first view
            linearLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);

        }
    });

给出这个结果:

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2015-12-12
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多