布局是指页面的控件的摆放样式。
在Android中使用.xml格式来控制布局。
一、布局分类:
1、线性布局
2、相对布局
二、布局的优化技巧:
1、比例划分(线性布局特有)
2、布局嵌套
一、布局分类:
1、线性布局(LinearLayout):内部的控件全部横向或者纵向一字排布。
这里只介绍几个基本的属性设置,刚开始学也没有贪多。
设置方向:
android:orientation="horizontal" //横向排布
android:orientation="vertical" //纵向排布
设置背景颜色(可参考RGB色表:https://www.sioe.cn/yingyong/yanse-rgb-16/)
android:background="#9400D3"
设置外边距
//同时设置四个方向的外边距
android:layout_margin="10dp" //本元素离上下左右间的距离
//也可以单独设置某个方向的外边距
android:layout_marginBottom //离某元素底边缘的距离
android:layout_marginLeft //离某元素左边缘的距离
android:layout_marginRight //离某元素右边缘的距离
android:layout_marginTop //离某元素上边缘的距离
android:layout_marginStart //本元素里开始的位置的距离
android:layout_marginEnd //本元素里结束位置的距离
设置内边距
//同时设置四个方向的内边距
android:padding //指定布局与子布局的间距
//也可以单独设置某个方向的内边距
android:paddingLeft //指定布局左边与子布局的间距
android:paddingTop //指定布局上边与子布局的间距
android:paddingRight //指定布局右边与子布局的间距
android:paddingBottom //指定布局下边与子布局的间距
android:paddingStart //指定布局左边与子布局的间距与android:paddingLeft相同
android:paddingEnd //指定布局右边与子布局的间距与android:paddingRight相同
设置重力方向(一般默认为从左上方开始,符合人们的阅读习惯)
android:gravity="bottom|right" //设置为在右下方
2、相对布局(RelativeLayout):内部的控件以某个其他的控件为参考系,在参考系的某个方位。
因为这种布局是相对于其他控件来进行布局的,所以要给控件一个名字,供其他控件布局参考使用
android:id="@+id/名字"
设置相对位置
android:layout_below //在某元素的下方
android:layout_above //在某元素的的上方
android:layout_toLeftOf //在某元素的左边
android:layout_toRightOf //在某元素的右边
android:layout_alignTop //本元素的上边缘和某元素的的上边缘对齐
android:layout_alignLeft //本元素的左边缘和某元素的的左边缘对齐
android:layout_alignBottom //本元素的下边缘和某元素的的下边缘对齐
android:layout_alignRight //本元素的右边缘和某元素的的右边缘对齐
经过初步学习使用这两种部件进行模拟计算器的布局,但是没有很好的去利用好线性布局和相对布局的特性,导致做出来的布局效果非常差。我犯得最严重的问题就是过多的去使用相对布局但是又用的不准确导致做成的布局效果不堪入目。而且不具备很好的适配性。
所以后面的学习很好的解决了我的问题并且对我原来的布局进行了优化。
二、布局的优化技巧
1、比例划分
前提是线性布局,内部元素可以按照比例划分
需要设置权重:
android:layout_weight=" "
纵向布局只能分内部控件的高度,横向布局只能分内部控件的宽度。
建议给要分比例的宽度或者高度写成0dp。
2、布局嵌套
任意的布局都可以看做一个整体,整体又可以成为另一个布局的内部控件
下面以模拟手机计算器布局为例,我通过使用线性布局的比例划分和布局嵌套优化了一下
思路:整体上采用纵向的线性布局,并通过比例划分使其具有更好的适配性。然后在其中某几个布局中又嵌入了横向的使用比例划分的线性布局。
不足是没有使用相对布局
代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.hello.MainActivity$PlaceholderFragment" >
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:background="#808080" />
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#A9A9A9"
android:gravity="bottom|right"
android:textSize=