一、开发背景
郭霖《第一行代码(第二版)》中第3.3.4百分比布局里面的分享,遇到的问题及其这个百分比布局的总结。
二、使用步骤
1. 添加依赖:书本上是
compile 'com.android.support:percent:24.2.1'
你会发现报错,无法加载成功。修改成即可!
compile 'com.android.support:percent:25.1.0'
那么为什么会出现这种情况呢:是因为依赖库里面已经更新了这个库,同时你也更新了appcompat-v7库,所以他才会给你报错,强制让你改成相应的版本。
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:percent:25.1.0'
两者对应即可。
2.好了之后别忘记 Sync Now(位于Android Studio右上角),后面我们就可以使用百分比布局了。
3.百分比布局的使用:
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_percentage"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn1"
android:layout_gravity="left|top"
android:background="@color/colorAccent"
android:text="5"
app:layout_heightPercent="20%"
app:layout_widthPercent="33.333%" />
<Button
android:id="@+id/btn5"
android:layout_gravity="center|top"
android:background="@color/colorPrimary"
android:text="2"
app:layout_heightPercent="20%"
app:layout_widthPercent="33.333%" />
<Button
android:id="@+id/btn2"
android:layout_gravity="right|top"
android:background="@color/colorAccent"
android:text="0"
app:layout_heightPercent="20%"
app:layout_widthPercent="33.333%" />
<Button
android:id="@+id/btn3"
android:layout_gravity="left|bottom"
android:text="百分比3"
app:layout_heightPercent="80%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/btn7"
android:layout_gravity="right|bottom"
android:background="#ffc"
android:gravity="top"
android:text="百分比3"
app:layout_heightPercent="80%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/btn4"
android:layout_gravity="right|bottom"
android:background="#fbb"
android:text="百分比4"
app:layout_heightPercent="20%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/btn6"
android:layout_gravity="center|right"
android:background="#fbb"
android:text="百分比6"
app:layout_heightPercent="20%"
app:layout_widthPercent="50%" />
</android.support.percent.PercentFrameLayout>
4.对应的布局是这样的:
三、总结
优点:可以按比例进行设置布局;
缺点:只能根据单方向只能放置3个控件或者布局,并且不好控制,相对有点鸡肋。处理的方法是horizontal和vertical方向百分比用的次数不超过3次。如果布局比较复杂,可用 LinearLayout 和 RelativeLayout 来完成。