android linearlayout 的gravity屬性

gravity屬性的意思可以說衆所周知我就不介紹了。分享下我遇到的問題。先看代碼吧。

問題是:gravity在父佈局中控制子佈局的位置和在子佈局中layout_gravity控制子佈局在父佈局中的位置。

效果想讓textview居屏幕中心。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>

我們可以先在父佈局中來控制子佈局的位置。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>

效果是:這裏寫圖片描述

既然我們在父佈局中可以控制,那麼在子佈局呢?對於線性佈局的排列方式我就不介紹了大家都知道。
接下里代碼寫寫看:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/hello_world" />

</LinearLayout>

效果卻是:這裏寫圖片描述

通過現象可以發現,子佈局如果調整在父佈局(針對線性佈局)中的位置如果線性佈局是水平的那麼子佈局layout_gravity=center效果只能垂直居中,如果是垂直的話,子佈局是水平居中的。造成這種情況的原因是什麼我不知道,如果有知道的不妨留個言。

發佈了17 篇原創文章 · 獲贊 34 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章