android佈局RelativeLayout中android-gravity=_center_horizontal_和android-la

RelativeLayout中設置居中的方法有兩個,一個是android:gravity="center_horizontal"還有一個是 android:layout_centerHorizontal=“true”

那麼他們有啥區別呢?
首先:android:gravity=“center_horizontal”

      <!--對於自身的內容,是水平居中的 -->
      <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="75dp"
            android:gravity="center_horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="賬號:12345678" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密碼:1234" />
        </RelativeLayout>

效果:圖片.png
然後是:android:layout_centerHorizontal=“true”

      <!--水平居中於父視圖 -->
      <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="75dp" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="賬號:12345678" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="密碼:1234" />
        </RelativeLayout>

效果:圖片.png

所以得出結論:
1.RelativeLayout的實際內容的寬高根據所有子視圖中的最大寬高所決定;
2.對於android:gravity=“center_horizontal”,對於自身的內容是水平居中的,但並不會設置其中所有子視圖的對齊值;
3.對於android:layout_centerHorizontal=“true”,則只是針對子視圖自身水平居中於父視圖;
4.例子中顯然android:gravity="center_horizontal"的效果比較好,因爲既可以做到子視圖居中,又可以讓子視圖對齊;
5.用哪個方法根據實際情況而定。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章