一,前提理解
在LinearLayout布局中:
对于android:orientation="horizontal",我们可以理解为默认情况下LinearLayout的多个子控件必须在
水平方向从左至右依次摆放,不可以左边空一部分不摆放任何控件而在水平方向中间的某处摆放一个控件,而在竖直方向则没有这个限制,本文后面会说到在给android:orientation="horizontal"类型的LinearLayout中的某个子控件使用android:layout_gravity="center"属性时,发现在水平方向没效果,只在竖直方向有效果,其结果是子控件会摆放在靠左居中的位置,需要说明的是android:layout_gravity="center"只是其中一个例子,其实对于horizontal其他水平方向的属性也无效,下面的两种情况也同意,不在说明了。
对于android:orientation="vertical",我们可以理解为默认情况下LinearLayout的多个子控件必须在竖直方向依次摆放,不可以上边空一部分不摆放任何控件而在竖直方向的中间某处摆放一个控件,而在水平方向则没有这个限制。本文后面会说到在给android:orientation="vertical"类型的LinearLayout中的某个子控件使用android:layout_gravity="center"属性时,发现在竖直方向没效果,只在水平方向有效果,其结果是子控件会摆放在屏幕上方居中的位置。
在RelativeLayout布局中:
我们可以理解为默认情况下RelativeLayout的多个子控件必须从左上角依次依次摆放,而不可以空一块地,在非左上角的某处摆放控件,后面会发现给RelativeLayout的某个子控件使用android:layout_gravity="center"属性,无效果,该子控件任然会摆放在屏幕的左上角,就是这个原因。
二,问题展示
在LinearLayout布局中:
对于android:orientation="horizontal"的问题展示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_gravity="center"
android:layout_width="@dimen/x160"
android:layout_height="@dimen/y133"
android:background="#2E8B57"/>
</LinearLayout>
结果:
在LinearLayout布局中:
对于android:orientation="horizontal"的问题展示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_gravity="center"
android:layout_width="@dimen/x160"
android:layout_height="@dimen/y133"
android:background="#2E8B57"/>
</LinearLayout>
结果:
在RelativeLayout布局中:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="@dimen/x160"
android:layout_height="@dimen/y133"
android:layout_gravity="center"
android:background="#2E8B57" />
</RelativeLayout>
结果:
三,解决办法
首先,这不是问题,也不是debug,我们要做的是了解它的特点,之后,再根据其特点去实现自己想要的效果,例如对于LinearLayout我们可以通过再引入一个水平方向或竖直方向fill_parent的LinearLayout再加上android:gravity="center"等属性的使用(将目标控件放在该新引入的LinearLayout中),来实现我们要的效果。其中引入新的fill_parent类型的LinearLayout的目的就是为了获取一个某一方向填充父元素的控件,这样就避开了顺序摆放的特点因为一个元素就占满一个方向了,然后再在新引入的LinearLayout中使用android:gravity="center",实现目标控件的居中