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.用哪个方法根据实际情况而定。

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