写给初学者22_android_百分比布局

来源:互联网 发布:js qq客服代码 编辑:程序博客网 时间:2024/06/11 08:11

安卓22_百分比布局


日常开发中我们使用LinearLayout来进行开发布局,并且活用layout-weight属性会为我们的开发节省很多得时间,并且一定程度上解决了开发中的适配问题。但是LinearLayout的局限在于我们只能有两个方向上的摆放,不怎么灵活。这个时候我们会去怀念RelativeLayout。不过RelativeLayout却没有layout-weight这样的布局参数可以设置。确实很让人头疼,这个时候SDK提出了一种全新的布局方式,百分比布局。

分为两种

  • PercentFrameLayout
  • PercentRelativeLayout

可以看到几乎只是在帧布局和相对布局上做了扩展。

使用

这里以PercentRelativeLayout为例。

添加依赖

在APP模块下添加一个依赖。

 compile 'com.android.support:percent:23.4.0'

至于版本根据合适选择就好。添加后需要同步一下项目。

直接使用

<?xml version="1.0" encoding="utf-8"?><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"><TextView    android:layout_centerInParent="true"    android:background="#2d7d9a"    android:gravity="center"    android:text="Center"    app:layout_heightPercent="50%"    app:layout_widthPercent="50%" /><TextView    android:background="#2d7d9a"    android:gravity="center"    android:text="left|top"    app:layout_heightPercent="25%"    app:layout_widthPercent="25%" /><TextView    android:layout_alignParentRight="true"    android:background="#2d7d9a"    android:gravity="center"    android:text="right|top"    app:layout_heightPercent="25%"    app:layout_widthPercent="25%" /><TextView    android:layout_alignParentBottom="true"    android:background="#2d7d9a"    android:gravity="center"    android:text="left|bottom"    app:layout_heightPercent="25%"    app:layout_widthPercent="25%" /><TextView    android:layout_alignParentBottom="true"    android:layout_alignParentRight="true"    android:background="#2d7d9a"    android:gravity="center"    android:text="right|bottom"    app:layout_heightPercent="25%"    app:layout_widthPercent="25%" /></android.support.percent.PercentRelativeLayout>

注意点

  1. 写出完整的包名
  2. 需要声明一个命名空间
  3. 使用的是layout_widthPercent属性
  4. 如果AndroidStudio版本比较低是无法预览的,但是不影响结果

结果


这里简单的使用就是确定宽和高的比例,但是可以看出功能已经非常强大了,结合了RelativeLayout的特点和比例特点。所在这当中RelativeLayout的属性特点你依旧可以继续爽快的应用。

布局参数

  • layout_widthPercent控件宽度为父容器的宽的百分比
  • layout_heightPercent控件高度为父容器的高的百分比
  • layout_marginPercent
  • layout_marginLeftPercent控件与左边控件的距离为父容器的宽度的百分比
  • layout_marginTopPercent控件与上方控件的距离为父容器的高度的百分比
  • layout_marginRightPercent控件与右边控件的距离为父容器的宽度的百分比
  • layout_marginBottomPercent控件与下方控件的距离为父容器的高度的百分比
0 0