RelativeLayout和LinearLayout中的子控件layout_gravity="center"的问题解决

一,前提理解

在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",实现目标控件的居中
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值