PercentFrameLayout(百分比布局)的基本使用

前面的3中布局,LinearLayout、RelativeLayout、FrameLayout都是从Android1.0中就开始支持了,一直沿用到现在,可以说是满足了绝大多数场景的界面设计需求。不过细心的你会发现,只有LinearLayout支持使用android:layout_weight属性来实现按比例指定控件大小的功能,其他两种布局都不支持比如说,如果想用RelativeLayout来实现两个按钮平分布局宽度的效果,则是比较困难的。

为此,Android引入了一种全新的布局方式来解决此问题-----百分比布局。在这种布局中,我们不再使用wrap_content、match_parent等方式来指定控件的大小,而是允许直接指定控件在布局中所占的百分比,这样的话就可以轻松实现平分布局甚至是任意比例分割布局效果了。

由于LinearLayout本身已经支持按比例指定控件的大小了,因此百分比布局属于新增布局,那么怎么才能做到让新增布局在所有Android版本上都能使用呢?为此,Android团队将百分比布局定义在了suppor库当中,我们只需要在项目的build.gradle中添加百分比布局库的依赖,就能保证百分比布局在Android所有系统版本上的兼容性了。

打开app/build.gradle文件,在dependencies闭包中添加以下内容:

implementation'com.android.support:percent:28.0.0'

点击右上方的Sync Now,然后gradle会开始进行同步,把我们新添加的百分比布局库引入到项目当中。

接下来修改activity_main.xml中的代码:

<?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: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:layout_gravity="right|bottom"
        android:text="btn4"
        android:textAllCaps="false"
        app:layout_heightPercent="50%"
        app:layout_widthPercent="50%" />


</android.support.percent.PercentFrameLayout>

效果图:

最外层我们使用了PercentFrameLayout,由于百分比布局并不是内置在系统SDK当中的,所以需要把完整的包路径写出来。然后还必须定义一个app的命名空间,这样才能使用百分比布局的自定义属性。

在PercentFrameLayout中我们定义了4个按钮,

使用app:layout_widthPercent属性将各个按钮的宽度指定为布局的50%,

使用app:layout_heightPercent属性将各个按钮的高度指定为布局的50%。

这里之所以可以使用app前缀的属性就是因为刚才定义了app的命名空间,当然我们一直能使用android前缀的属性也是同样的道理。

不过PercentFrameLayout还是会继承FrameLayout的特性,即所有的控件默认都是摆放在布局的左上角。那么,为了让这4个按钮不会重叠,这里还是借助了layout_gravity属性来分别将4个按钮放置在布局的左上,右上,左下,右下4个位置。

 

 

猜你喜欢

转载自blog.csdn.net/android_studying/article/details/85935240
今日推荐