日常开发中我们使用LinearLayout来进行开发布局,并且活用layout-weight属性会为我们的开发节省很多得时间,并且一定程度上解决了开发中的适配问题。但是LinearLayout的局限在于我们只能有两个方向上的摆放,不怎么灵活。这个时候我们会去怀念RelativeLayout。不过RelativeLayout却没有layout-weight这样的布局参数可以设置。确实很让人头疼,这个时候SDK提出了一种全新的布局方式,百分比布局。
分为两种
- PercentFrameLayout
- PercentRelativeLayout
可以看到几乎只是在帧布局和相对布局上做了扩展。
使用
这里以PercentRelativeLayout为例。
添加依赖
在APP模块下添加一个依赖。
compile 'com.android.support:percent:23.4.0'
至于版本根据合适选择就好。添加后需要同步一下项目。
直接使用
<?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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_centerInParent="true"
android:background="#2d7d9a"
android:gravity="center"
android:text="Center"
app:layout_heightPercent="50%"
app:layout_widthPercent="50%" />
<TextView
android:background="#2d7d9a"
android:gravity="center"
android:text="left|top"
app:layout_heightPercent="25%"
app:layout_widthPercent="25%" />
<TextView
android:layout_alignParentRight="true"
android:background="#2d7d9a"
android:gravity="center"
android:text="right|top"
app:layout_heightPercent="25%"
app:layout_widthPercent="25%" />
<TextView
android:layout_alignParentBottom="true"
android:background="#2d7d9a"
android:gravity="center"
android:text="left|bottom"
app:layout_heightPercent="25%"
app:layout_widthPercent="25%" />
<TextView
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#2d7d9a"
android:gravity="center"
android:text="right|bottom"
app:layout_heightPercent="25%"
app:layout_widthPercent="25%" />
</android.support.percent.PercentRelativeLayout>
注意点
- 写出完整的包名
- 需要声明一个命名空间
- 使用的是layout_widthPercent属性
- 如果AndroidStudio版本比较低是无法预览的,但是不影响结果