Android布局学习(四)——百分比布局Percent?Layout

注意,该布局已经被弃用,推荐布局:ConstraintLayout

代码接着上文:《Android布局学习(三)——帧布局FrameLayout》继续编写。

学了三种布局,其中只有 线性布局LinearLayout支持用layout_weight实现了按找比例指定控件大小的功能。所以Android有引用了一种百分比布局的方式实现任意比例的分割布局效果。

百分比布局时帧布局FrameLayout相对布局RelativeLayout的扩展,提供了PercentFrameLayoutPercentRelativeLayout 两种新的布局方式。

一、新增布局的解决方案

参考资料:
关于 build.gradle的介绍
使用此方案踩过的坑

百分比布局是新增的布局,怎么在所有的Android版本上使用呢?Android团队将其定义在了support库中,只需要在build.gradle库在添加百分比布局的依赖,就能保证兼容性了。

只需要在dependencies{}中添加以下内容即可实现兼容:

implementation 'androidx.percentlayout:percentlayout:1.0.0'

在这里插入图片描述
修改完AS顶部会有这个提示:
在这里插入图片描述
点击Sync Nowgradle就会开始同步了

二、体验百分比布局

注意,百分比布局不是内置的布局,所以要写完整的包路径,然后再定义一个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指定控件宽高。

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值