Android AutoLayout 学习笔记

来源:互联网 发布:ie8登录不了淘宝 编辑:程序博客网 时间:2024/06/04 18:13

一、概述
最初虽然对Android开发稍有学习,但涉猎不深,往往项目做完就交接给别人了,没有对机型适配以及UI问题做更多了解。之后从事iOS开发,发现iOS的UI适配真的比Android适配省心好多。由于公司业务的需要,最近研究下Android开发能否找到跟iOS开发一样的省心的适配方案,略作整理,同时做下记录。

相关链接:
1、百分比屏幕适配方案
2、Android 百分比布局库(percent-support-lib) 解析与扩展
3、Android 增强版百分比布局库 为了适配而扩展

对比说明:
1、百分比布局库的用法:提供了PercentRelativeLayout、PercentFrameLayout供大家在编写的时候,对于以下属性:

layout_widthPercent、layout_heightPercent、 layout_marginPercent、layout_marginLeftPercent、 layout_marginTopPercent、layout_marginRightPercent、 layout_marginBottomPercent、layout_marginStartPercent、layout_marginEndPercent。

可以使用百分比进行设置宽、高、边距,在适配上提供了极大的便利,但是在使用过程中,存在一些场景无法得到满足。

2、针对1中无法得到满足的场景进行优化,得到了百分比布局库的扩展库:

1、当使用图片时,无法设置宽高的比例比如我们的图片宽高是200*100的,我们在使用过程中我们设置宽高为20%、10%,这样会造成图片的比例失调。为什么呢?因为20%参考的是屏幕的宽度,而10%参考的是屏幕的高度。2、很难使用百分比定义一个正方形的控件比如,我现在界面的右下角有一个FloatingActionButton,我希望其宽度和高度都为屏幕宽度的10%,很难做到。3、一个控件的margin四个方向值一致有些时候,我设置margin,我希望四边的边距一致的,但是如果目前设置5%,会造成,上下为高度的5%,左右边距为宽度的5%。

综合上述这些问题,发现目前的percent-support-lib并不能完全满足需求,所以对其进行扩展。在布局的时候可以设定参考宽度还是高度,可以写成10%w,10%h。也就是在不改变原库的用法的前提下,添加一些额外的支持。

3、用法
Android Studio的用户,直接:

dependencies {    //...    compile 'com.zhy:percent-support-extends:1.0.7'}

不需要导入官方的percent-support-lib了。

对应的三个类分别为:

com.zhy.android.percent.support.PercentLinearLayoutcom.zhy.android.percent.support.PercentRelativeLayoutcom.zhy.android.percent.support.PercentFrameLayout

支持的属性 :

layout_heightPercentlayout_widthPercentlayout_marginBottomPercentlayout_marginEndPercentlayout_marginLeftPercentlayout_marginPercentlayout_marginRightPercentlayout_marginStartPercentlayout_marginTopPercentlayout_textSizePercentlayout_maxWidthPercentlayout_maxHeightPercentlayout_minWidthPercentlayout_minHeightPercentlayout_paddingPercentlayout_paddingTopPercentlayout_paddingBottomPercentlayout_paddingLeftPercentlayout_paddingRightPercent

对应值可以取:10%w , 10%h , 10% , 10%sw , 10%sh

对于ScrollView理论上是不支持的,因为如果PercentLinearLayout在ScrollView中,那么高度的模式肯定是UNSPECIFIED,那么理论上来说高度是无限制的,也就是依赖于子View的高度,而百分比布局的高度是依赖于父View的高度的,所以是互斥的。而考虑到编写代码的时候,大多参考的是屏幕(android.R.id.content)的高度,所以如果在ScrollView中,编写10%h,这个百分比是依赖于屏幕高度的(不包括ActionBar的高度)。

0 0