android布局RelativeLayout中android:gravity="center_horizontal"和android:layout_centerHorizontal="true...

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容