【问题标题】:How to vertically center a view inside vertical linear layout?如何在垂直线性布局中垂直居中视图?
【发布时间】:2019-03-03 21:36:53
【问题描述】:

我有一个垂直线性布局,它包裹了另一个垂直线性布局。

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

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

<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将生效。但这不是浪费吗?

【问题讨论】:

  • 必须是线性布局吗?您可以只使用相对布局并赋予属性 android:centerVeritical="true"
  • 或者使用约束布局

标签: android android-layout android-linearlayout center


【解决方案1】:
<?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 下方

【讨论】:

  • 你能解释一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 2017-01-18
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多