安卓进阶:Percent Support Library使用
安卓手机有很多种机型、不同的屏幕、不同的分辨率,所以对安卓软件屏幕适配这一块的问题一直都不怎么友好。布局方面如果是线性布局LInearLayout的话还好一点,可以使用layout_weight的权重比可以实现控件按屏幕比例来排放。
但是对于相对布局或者说帧布局这些没有layout_weight这个属性的布局来说就比较啰嗦了,如果要实现屏幕比例布局还得在外面再嵌套一个LinearLayout,本来使用相对布局的初衷就是减少布局的嵌套使用的,这样反复嵌套LinearLayout反而得不偿失。
为了解决这个问题谷歌推出了一个百分比布局兼容的函数库:Android Percent Support Library.现在支持RelativeLayout和FrameLayout的百分比布局,不过听说有人开源了对LinearLayout的百分比支持,我没试过。
使用:
Percent函数库属于Support Library,在使用它之前得先在app目录下的buile.gradle文件中的dependencies{}中加入依赖
| 1 | compile "com.android.support:percent:26.+" | 
注意对应自己的SDK版本,我这里是26版本以上的
重新rebuild一下项目就可以使用Percent函数库中的类了
现在我使用这个函数库中的其中一个类写一个布局文件
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <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">    <TextView        android:id="@+id/tv1"        android:layout_width="0dp"        android:layout_height="0dp"        android:background="#000000"        app:layout_heightPercent="20%"        app:layout_widthPercent="70%"/>    <TextView        android:id="@+id/tv2"        android:layout_width="0dp"        android:layout_height="0dp"        android:layout_below="@id/tv1"        android:background="#cfc61d"        app:layout_heightPercent="70%"        app:layout_widthPercent="20%"/></android.support.percent.PercentRelativeLayout> | 
可以看到我给定的两个控件的宽和高都是0,控件大小完全是由百分比(红色字体)决定的。而且可以看到在引用百分比这个方法时,在他们前面都加了app:作为前缀引用,因为新增加的属性并不是位于Android命名的空间之内的。
特别提醒:注意看我使用的布局(红色背景内容)是PercentRelativeLayout而不是RelativeLayout
效果:

Percent函数库包含以下三个类:
- PercentFrameLayout
- PercentRelativeLayout
- PercentLayoutHelper
PercentRelativeLayout和PercentFrameLayout这两个类分别是对RelativeLayout和FrameLayout两个类的继承。因此我们还是可以使用两个父类的属性和功能,同时PercentRelativeLayouyt和PercentFrameLayout两个类扩展的百分比特性也可以使用,他们在xml文件中增加的配置属性如下:
- layout_widthPercent:用百分比表示宽度
- layout_heightPercnet:用百分比表示高度
- layout_marginPercent:用百分比表示View之间的间隔
- layout_marginLeftPercent:用百分比表示左边的间隔
- layout_marginTopPercent:用百分比表示顶部的间隔
- layout_marginRightPercent:用百分比表示右边的间隔
- layout_marginBottomPercent:用百分比表示底部的间隔
- layout_marginStartPercent:用百分比表示距离第一个View的距离
- layout_marginEndPercent:用百分比表示距离最后一个View的距离
- layout_aspectRatio:用百分比表示View的宽高比
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号