如何在垂直线性布局内垂直居中放置视图?

时间:2018-09-27 22:34:27

标签: android android-layout android-linearlayout center

我有一个垂直的线性布局,可以包裹另一个垂直的线性布局。

如何使内部线性布局垂直居中?

据我所知,垂直线性布局迫使其子级从左上角开始定位。

<LL vertical> //outer

  <LL vertical> //inner - is used to group
    <textView> //just a view to be vertically centered
    </textView>
  <LL vertical>

    <anotherView/>

</LL vertical>

当我删除外部线性布局时,我看到内部线性布局垂直于其父级居中。

如何实现相同的垂直居中?分组需要外部线性布局。

我可以将垂直LL与水平LL包裹在一起,然后其子元素的vertical_center将有效。但这不是浪费吗?

1 个答案:

答案 0 :(得分:0)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

   <LinearLayout
       android:id="@+id/layout1"
       android:layout_width="match_parent"
       android:layout_height="0dp"
       android:layout_weight="1">

   </LinearLayout>

   <LinearLayout
       android:id="@+id/inner_layout"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:gravity="center_vertical"
       android:orientation="vertical">

       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Text 1" />
   </LinearLayout>

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="0dp"
       android:id="@+id/layout2"
       android:layout_weight="1">

       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Another View" />
   </LinearLayout>

</LinearLayout>

可以像上面的布局一样实现。将所有位于上方的视图置于layout1的内部布局中,所有这些视图应位于layout2的inner_layout下面