Android 官方百分比适配库

来源:互联网 发布:网络选修课app 编辑:程序博客网 时间:2024/05/14 05:55

Android Percent Support Lib

概述

由于 Android 机型种类众多,屏幕的碎片化也非常的严重。这对于 UI 布局的适配来说也是非常麻烦的一个事情。一种做法是:以不同分辨率建立相对应的一套 UI——重复运动而且增加 APK 的大小。另一种就是在 LinearLayout 布局中使用 layout_weight 属性来实现按比例来适配—— Google 并不提倡使用 weight 权重,因为这样会在加载布局时造成大量的计算,影响性能。

现在好了,Google 官方公布了一个类似于 CSS 的百分比来布局的库(android.support.percent)。使用百分比来做 UI 布局,学会使用这个库进行布局,真是一劳永逸啊。

效果图

以下手机分辨率分别是:480*840、768*1280、1080*1920、1440*2560。可以看到只是用一个 layout 文件就能达到很好的适配效果。
这里写图片描述这里写图片描述这里写图片描述这里写图片描述

支持的布局与属性

支持如下布局(顾名思义就能知道对应的是哪些原布局):

  • PercentRelativeLayout
  • PercentLinearLayout(这可是Hongyang哥提供的哟)
  • PercentFrameLayout

支持的如下属性:

  • heightPercent
  • widthPercent
  • marginBottomPercent
  • marginEndPercent
  • marginLeftPercent
  • marginPercent
  • marginRightPercent
  • marginStartPercent
  • marginTopPercent

如何使用

首先需要满足如下要求:

  • Android SDK v22
  • Android Build Tools v22.0.1
  • Android Percent Support Repository v22.2.0
  • Android Support v4 Repository v22.2.0

然后在 build.gradle 下添加:

dependencies {    compile 'com.android.support:percent:22.2.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:layout_width="match_parent"    android:layout_height="match_parent">    <View        android:id="@+id/view1"        android:layout_width="0dp"        android:layout_height="0dp"        android:background="@color/accent_material_light"        app:layout_heightPercent="25%"        app:layout_widthPercent="70%" />    <View        android:id="@+id/view2"        android:layout_width="0dp"        android:layout_height="0dp"        android:layout_alignParentRight="true"        android:background="#E91E63"        app:layout_heightPercent="20%"        app:layout_widthPercent="30%" />    <View        android:id="@+id/view3"        android:layout_width="0dp"        android:layout_height="0dp"        android:layout_below="@id/view1"        android:background="#2196F3"        app:layout_heightPercent="50%"        app:layout_widthPercent="70%" />    <View        android:id="@+id/view4"        android:layout_width="0dp"        android:layout_height="0dp"        android:layout_alignParentRight="true"        android:layout_below="@id/view2"        android:background="#FF9800"        app:layout_heightPercent="80%"        app:layout_widthPercent="30%" />    <View        android:layout_width="0dp"        android:layout_height="0dp"        android:layout_below="@id/view3"        android:background="#F44336"        app:layout_heightPercent="25%"        app:layout_widthPercent="70%" /></android.support.percent.PercentRelativeLayout>
0 0
原创粉丝点击