View和ViewGroup
Android的UI界面都是View和ViewGroup及其子类组合而成的。View是所有UI组件的父类,其子类称为组件(Widget);ViewGroup是布局管理器,本身也是继承自View类,其子类称为布局(Layout)。Android布局管理器的类图如下:
![]()
属性
android:gravity 用于控制所包含的子元素的对齐方式,其值有top、bottom、left、right、center、center_horizontal、center_vertical、fill、fill_horizontal、 clip_vertical、clip_horizontal,以上的值可单独出现(如:android:layout_gravity="center_horizontal"),也可以组合的形式出现(如:android:layout_gravity="center_horizontal|bottom")
android:layout_gravity 设置该子View在父容器中的对齐方式
android:layout_margin 设置View和View之间的距离
android:padding 设置View里面的内容相对于View的边框的距离

ViewGroup的种类
ViewGroup有很多种类,常见的有LinearLayout、RelativeLayout、FrameLayout、AbsoluteLayout、GirdLayout、TableLayout。其中,LinearLayout和RelativeLayout使用的最多的两种。
LinearLayout
LinearLayout,即线性布局。顾名思义,LinearLayout布局里的View一个挨着一个,成线性排列。
属性
android:orientation 设置LinearLayout内View的排列方式,可以设置horizontal(水平排列,默认值)、vertical(垂直排列)两个值的其中之一
android:layout_weight 指定该子元素在LinearLayout中所占的权重(注意:该属性只有在LinearLayout布局中才有效)
效果演示
xml布局文件:


效果图:

android:layout_weight详解
-
android:layout_weight,又称权重,只有在LinearLayout布局中,该属性才有效;
-
当LinearLayout布局中只有唯一一个有权重的子View时,不管该子View的权重设为多少,该子View都会占满父容器剩下的空间;
-
在android:orientation="horizontal"时,当LinearLayout布局中不止有一个子View有android:layout_weight(即权重)属性,并且子View的权重不一样的时候,设置android:layout_width为match_parent和wrap_content(或0dp,后面会有解释)时,会造成两种截然相反的效果。
-
设置android:layout_width="match_parent"时:
xml布局文件:
效果图:
可以看到layout_weight=”1”的占了三分之二,而layout_weight=”2”的占了三分之一。
-
设置android:layout_width="wrap_content"时:
xml布局文件:
效果图:
可以看到layout_weight=”1”的占了三分之一,而layout_weight=”2”的占了三分之二。
总结:
android:orientation为horizontal时:
-
layout_width设置为match_parent的时候,weight权值越小所代表的是你的控件要优先尽可能的大,但这个大是有限度的,即match_parent;
-
layout_width设置为wrap_content的时候,weight权值越小所代表的是你的控件要优先尽可能的小,但这个小是有限度的,即wrap_content;
-
当使用weight属性时,将width设为0dp即可,效果跟设成wrap_content是一样的。
android:orientation为vertical时与为horizontal道理一样,只不过变成了layout_height为match_parent和wrap_content时会有截然不同的效果。
RelativeLayout
RelativeLayout,相对布局,这里的相对有两层含义。一是子View相对于父容器的位置,二是父容器中一个子View相对于另一个子View的位置。
属性
子View与父容器的相对位置
(以下属性的值为boolean类型,即只有false和true,默认为false)
android:layout_centerHorizontal 控制子View是否位于父容器的水平居中位置
android:layout_centerVertical 控制子View是否位于父容器的垂直居中位置
android:layout_centerInParent 控制子View是否位于父容器的中央位置
android:layout_alignParentTop 控制子View是否与父容器顶端对齐
android:layout_alignParentBottom 控制子View是否与父容器底端对齐
android:layout_alignParentLeft 控制子View是否与父容器左边对齐
android:layout_alignParentRight 控制子View是否与父容器右边对齐
View与View的相对位置
android:layout_above 控制使用该属性的View位于给出ID的View的上方
android:layout_below 控制使用该属性的View位于给出ID的View的下方
android:layout_toLeftOf 控制使用该属性的View位于给出ID的View的左侧
android:layout_toRightOf 控制使用该属性的View位于给出ID的View的右侧
android:layout_alignTop 控制使用该属性的View与给出ID的View的上边界对齐
android:layout_alignBottom 控制使用该属性的View与给出ID的View的下边界对齐
android:layout_alignLeft 控制使用该属性的View与给出ID的View的左边界对齐
android:layout_alignRight 控制使用该属性的View与给出ID的View的右边界对齐
效果演示
xml布局文件:


效果图:

网友评论