注意,该布局已经被弃用,推荐布局:ConstraintLayout
代码接着上文:《Android布局学习(三)——帧布局FrameLayout》继续编写。
学了三种布局,其中只有 线性布局LinearLayout
支持用layout_weight
实现了按找比例指定控件大小的功能。所以Android有引用了一种百分比布局的方式实现任意比例的分割布局效果。
百分比布局时帧布局FrameLayout
和 相对布局RelativeLayout
的扩展,提供了PercentFrameLayout
和 PercentRelativeLayout
两种新的布局方式。
一、新增布局的解决方案
参考资料:
关于 build.gradle
的介绍
使用此方案踩过的坑
百分比布局是新增的布局,怎么在所有的Android版本上使用呢?Android团队将其定义在了support
库中,只需要在build.gradle
库在添加百分比布局的依赖,就能保证兼容性了。
只需要在dependencies{}
中添加以下内容即可实现兼容:
implementation 'androidx.percentlayout:percentlayout:1.0.0'
修改完AS顶部会有这个提示:
点击Sync Now
,gradle
就会开始同步了
二、体验百分比布局
注意,百分比布局不是内置的布局,所以要写完整的包路径,然后再定义一个app
的命名控件,才能使用百分比布局的自定义属性,然后借用命名空间app
设置布局占比。
<?xml version="1.0" encoding="utf-8"?>
<androidx.percentlayout.widget.PercentFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<Button
android:id="@+id/button1"
android:text="Button 1"
android:layout_gravity="left|top"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<Button
android:id="@+id/button2"
android:text="Button 2"
android:layout_gravity="right|top"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<Button
android:id="@+id/button3"
android:text="Button 3"
android:layout_gravity="left|bottom"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<Button
android:id="@+id/button4"
android:text="Button 4"
android:layout_gravity="right|bottom"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
</androidx.percentlayout.widget.PercentFrameLayout>
在写代码时,Android Stdio
会报这个错:
这个我就不解释了,忽略就好。来运行一下:
相同的,PercentFrameLayout
继承了FrameLayout
所有属性,PercentRelativeLayout
也继承了RelativeLayout
的所有属性,同样可以用app
指定控件宽高。