RelativeLayout控件居中详细解析(可能是最完美的方法)

在RelativeLayout中设置控件全部居中,需要注意在父布局的一些细节设置即可,现在给出完美的解决方法,先看实例:


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

    <VideoView
        android:id="@+id/video_play"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp" />

RelativeLayout>

RelativeLayout控件居中详细解析(可能是最完美的方法)_第1张图片

以上代码完美的实现了在RelativeLayout中的居中。

下面来看看另一种情况:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center">

    <VideoView
        android:id="@+id/video_play"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp" />

RelativeLayout>

对比之前的代码,仅修改了父布局中的width、height,改为wrap_content,gravity还是没改变。

RelativeLayout控件居中详细解析(可能是最完美的方法)_第2张图片

控件在RelativeLayout中就不居中了。

由此可见对于父布局的width、height的设置,对控件居中的实现是多么重要了。但是若项目实现中,非要把父布局设置成wrap_content,难道就没有别的方法了吗?答案当然是,有!

大家肯定留意到了父布局中的gravity居中的设置,其实这个就是解决居中问题的关键点。若你将父布局width、height设置成wrap_content之后,那么就不能使用android:gravity=”center”来控制控件居中了,而应该改成android:layout_gravity=”center”来使用即可。具体的代码为:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <VideoView
        android:id="@+id/video_play"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp" />

RelativeLayout>

这样就可以完美的解决问题了,在使用的过程要稍微留意一下就可以解决这些布局的小问题了。

现在和大家分享一下 android:layout_gravity、android:gravity=”center”的区别。
android:gravity 主要是对自身View的位置控制。
android:layout_gravity 主要用于设置View 或者 Layout 在其父组件中的对齐方式。

你可能感兴趣的:(Android开发技巧,android,relativelayout,控件,居中)