百分比布局

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

由于LinearLayout本身已经支持按比例指定控件的大小了,因此百分比布局只为FrameLayout和Relativelayout进行了功能扩展。


我们只需在项目的build.gradle中添加百分比布局库的依赖,就能保证百分比布局在Android所有系统版本上的兼容性了。

添加如下:

dependencies {
    compile 'com.android.support:percent:25.0.1'
}

接下来修改xml文件的代码就可以啦。

<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">
    <Button
        android:id="@+id/btn1"
        android:text="1"
        app:layout_widthPercent="50%"
        app:layout_heightPercent="50%"
        android:background="@color/colorAccent"
        android:layout_marginLeft="26dp"
        android:layout_marginStart="26dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="16dp" />

    <Button
        android:id="@+id/btn2"
        android:text="2"
        app:layout_widthPercent="30%"
        app:layout_heightPercent="20%"
        android:layout_marginRight="88dp"
        android:layout_marginEnd="88dp"
        android:layout_marginTop="16dp"
        android:layout_below="@+id/btn1"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:id="@+id/btn3"
        android:text="3"
        app:layout_widthPercent="30%"
        app:layout_heightPercent="30%"
        android:layout_below="@+id/btn2"
        android:layout_marginTop="8dp" />
</android.support.percent.PercentRelativeLayout>

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

使用app:layout_widthPercent=”50%”将按钮的宽度指定为布局的50%,
使用app:layout_heightPercent=”50%”将按钮的高度指定为布局的50%。

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

PercentRelativeLayout是继承了RelativeLayout的所有属性的,同样PercentFrameLayout是继承了FrameLayout的所有属性的。


以下为效果图:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值