代码之家  ›  专栏  ›  技术社区  ›  Sunny

在父视图和某个视图下的中心视图

  •  1
  • Sunny  · 技术社区  · 8 年前
    1. View A将位于父对象的中心
    2. B( TextView )会出现在父对象的顶部。
    3. 但随着视图B的高度增加并到达视图A,则它应尽可能向下推视图A以显示其所有内容。

    如果我使用相对布局,我可以将视图a置于父视图的中心垂直位置,也可以放在视图B的下方,但两者都不能同时实现。 另外,只有当视图A在相对布局中低于视图B时,才有可能出现#3,但我无法使其首先位于父视图的中心,而视图B的高度不足以到达视图A。

    有人能提供一些建议吗? 谢谢

    1 回复  |  直到 8 年前
        1
  •  0
  •   Santhosh Joseph    8 年前

    试试这个:

    <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>
    

    以编程方式将第一个视图的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);
    
            }
        });
    

    给出这个结果:

    enter image description here

    希望这对你有帮助:)

    推荐文章