编写android视图有两种方式可以实现
1,通过配置xml来实现
2,通过动态编码来实现
通过第一种方式可以将视图和业务逻辑很好的分离开来,也是使用比较多的
第二种情况一般在需要动态改变页面布局的情况下使用android的View的设计主要使用了java的组合模式
组合模式:将对象以树形结构组织起来,以达成“部分-整体”的层次结构,使得客户端对单个对象和组合对象的使用具有一致性.
按照组合模式的定义,这里的单个对象可以具体到android的每一个基本组件(Button,CheckBox,TextView等等)
而组合对象是指那些实现了ViewGroup接口的对象
在android中,组合对象控制其内部所有单个对象的布局
有些组合对象本身也是UI组件可以拿来直接使用,如GridView,Spinner,ListView等等
而也有一些组合对象它们本身并不是UI组件,只是用于控制其内部所有单个对象的布局,也就是android中的布局对象android中比较常用的布局有LinearLayout,TableLayout和Relativelayout
LinearLayout:
主要属性
orientation:horizontal|vertical用来表示是水平布局还是垂直布局
layout_weight:相对于其他组件该组件的空间分配比率
假设水平布局,且有3个组件
如果3各组件的layout_width全部为wrap_content,layout_weight为1、2、1,
则第二个组件的水平空间是第一个和第3个的空间之和TableLayout
关键属性stretchColumns
android:stretchColumns="1,2"
stretchColumns属性用来指定哪一个column具备自动伸缩功能来匹配表格的宽度
表格的行
最常使用的是TableRow,用来表示表格的一行
除了使用TableRow我们也可是使用其他的View视图来作为TableLayout的children节点,那么这个视图将作为单独的一行存在,并占据着所有的column
注:TableLayout的children节点不能指定layout_width属性,它的值永远都是FILL_PARENT,但我们可以指定layout_height属性(默认值是wrap_content)
而Linerlayout的children节点layout_width属性和layout_height是必须要指定的
表格的列column
表格的哪一行的单元格数(cell)最多,那么该表格的列数就是该行的单元格数
表格的单元格cell
每一个TableRow的children节点都代表一个cell,相当于html标签里的td
但与html不同的是,在TableLayout里我们不能让一个cell占有两个或两个以上的column
就像html中的<tdcolspan="2">这种格式无法实现
另外我们可以对每一个cell指定layout_column属性,用来表示该cell是显示在哪一个column中,column的起始计数是从0开始的RelativeLayout
某一个组件的位置是相对于其他组件的位置来决定的
在与某个组件的比对过程中,所比对的组件是通过(@id/id)的方式来进行引用的,
因此在xml中声明新组件之前,应当首先声明与它进行比对的组件id
RelativeLayout所定义的布局规则rules
在xml中都是以layout_attribute的格式,这里只写出attribute
abovealignsachild'sbottomedgewithanotherchild'stopedge
belowalignsachild'stopedgewithanotherchild'sbottomedge
alignTopalignsachild'stopedgewithanotherchild'stopedge
alignBottomalignsachild'sbottomedgewithanotherchild'sbottomedge
alignBaselinealignsachild'sbaselinewithanotherchild'sbaseline
alignLeftalignsachild'sleftedgewithanotherchild'sleftedge
alignRightalignsachild'srightedgewithanotherchild'srightedge
alignParentLeftalignsthechild'sleftedgewithitsRelativeLayoutparent'sleftedgetrue|false
alignParentRightalignsthechild'srightedgewithitsRelativeLayoutparent'srightedgetrue|false
alignParentTopalignsthechild'stopedgewithitsRelativeLayoutparent'stopedgetrue|false
alignParentBottomalignsthechild'sbottomedgewithitsRelativeLayoutparent'sbottomedgetrue|false
centerHorizontalcentersthechildhorizontallywithrespecttotheboundsofitsRelativeLayoutparenttrue|false
centerVertivalcentersthechildverticallywithrespecttotheboundsofitsRelativeLayoutparenttrue|false
centerInParentcentersthechildwithrespecttotheboundsofitsRelativeLayoutparenttrue|false
toLeftOfalignsachild'srightedgewithanotherchild'sleftedge
toRightOfalignsachild'sleftedgewithanotherchild'srightedge
padding[Bottom|Left|Right|Top]=value
margin[Bottom|Left|Right|Top]=value
相比LinerLayout和TableLayout,RelativeLayout的构造最为复杂,功能也较为强大,缺点是可能会增加很多不必要的组件id来加大系统开销