从前面的文章学习中可以知道只有线性布局用layout_weight属性来实现比例指定控件大小的效果,其他两种布局都不支持,为此Android引入了一种全新的布局方式来解决此问题------百分比布局。在这种布局中,我们不再使用wrap_content,match_parent等方式来指定控件的大小,而是允许直接指定控件在布局中所占的百分比,这样的话就可以轻松实现平分布局甚至是任意比例分割布局的效果了。因为线性布局本身已经支持按比例指定控件的大小了,因此百分比布局只为帧布局和相对布局进行了功能扩展,提供了PercentFrameLayout和PercentRelativeLayout这两个全新的布局。为了在所有Android版本上都能使用百分比布局,Android团队将其定义在了support库当中,我们只需在项目的build.gradle中添加百分比布局库的依赖,就能保证百分比布局在Android所有系统版本上的兼容性了。
在app/dependencies闭包中添加如下内容:
dependencies {
implementation 'androidx.percentlayout:percentlayout:1.0.0'
}
当修改了任何的gradle文件时,Android Studio都会弹出一个如下图的窗口
只需点击sync now 然后gradle就会自动进行同步,把我们新添加的百分比布局引入到项目当中,接下来修改activity_main.xml文件当中的代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.percentlayout.widget.PercentFrameLayout
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/btn1"
android:layout_gravity="left|top"
android:text="btn1"
android:textAllCaps="false"
app:layout_heightPercent="50%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/btn2"
android:layout_gravity="right|top"
android:text="btn2"
android:textAllCaps="false"
app:layout_heightPercent="50%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/btn3"
android:layout_gravity="left|bottom"
android:text="btn3"
android:textAllCaps="false"
app:layout_heightPercent="50%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/btn4"
android:text="btn4"
android:layout_gravity="right|bottom"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%" />
</androidx.percentlayout.widget.PercentFrameLayout>
效果图: