程序界面(UI)——布局
布局,就是按照一定的规律调整内部控件的位置,当然也可以布局嵌套布局
1.线性布局(LinearLayout)
由android:orientation来指定排列方向,排列比较规则,xml文件最后用</LinearLayout>
结束
属性 | 方向 | 效果 | 备注 |
---|---|---|---|
vertical | 垂直 | 不能将高度设为match_parent 否则一个控件就占满垂直方向了 | |
horizontal | 水平 | 不能将宽度设为match_parent 否则一个控件就占满水平方向了 | |
此外还有个属性android:layout_gravity来控制对齐方式就不细说了
2.相对布局(RelativeLayout)
比较随意,控件可出现在任何位置
用**android:layout_xxx=“true”**来决定位置,xml文件最后用</RelativeLayout>
结束,挺容易摸索就不细说了
举例:
3.帧布局(FrameLayout)
所有控件默认叠在左上角,可以通过android:gravity来控制位置,xml文件最后用</FrameLayout>
结束,前面看过就不重复了。
4.百分比布局
前面三种布局中只有线性布局(LinearLayout)可以用layout_weight属性来按比例控制控件大小,因此百分比布局可以理解为对相对布局(RelativeLayout)和帧布局(FrameLayout)进行扩展,分别对应为PercentRelativeLayout和PercentFrameLayout。
要想用百分比布局,首先得添加依赖**(在app下的build.gradle中添加,不是最外层的那个)**:
我看的是《第一行代码》的第二版,书中给的代码如下
dependencies {
compile fileTree(dir: 'libs',include: ['*.jar'])
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:percent:24.2.1'
tesCompile 'junit:junit:4.12'
}
尝试后发现不行,百度后发现,在3.0版本中,compile 指令被标注为过时方法,新增了两个依赖指令,implementation和api
指令 | 含义 |
---|---|
api | 与compile相同,换句话说,用api替换原本的compile即可 |
implementation | 可以让module在编译时隐藏自己使用的依赖,可以减少build的使用时间 |
添加的代码应该为:
implementation 'com.android.support:percent:28.0.0'
//28.0.0对应的是上面的版本号,可改
然后按Sync Now进行同步,修改xml中的相应控件即可
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_gravity="left|top"
android:text="Button_1"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/button2"
android:layout_below="@id/view2"
android:layout_alignParentRight="true"
android:text="Button_2"
app:layout_heightPercent="25%"
app:layout_widthPercent="30%" />
<ImageView
android:id="@+id/image_view666"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_gravity="bottom"
android:layout_marginBottom="0dp"
android:src="@drawable/img_1"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%" />
<ImageView
android:id="@+id/image_view999"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_gravity="bottom"
android:layout_marginBottom="0dp"
android:src="@drawable/img_2"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%" />
<View
android:id="@+id/view1"
android:layout_below="@+id/button1"
android:background="#ff44aacc"
app:layout_heightPercent="25%"
app:layout_widthPercent="70%" />
<View
android:id="@+id/view2"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:background="#ff44aa"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%" />
</android.support.percent.PercentRelativeLayout>
效果: