本帖最后由 诗帆 于 2012-5-22 14:28 编辑
一、细说
layout_weight
目前最为推荐的Android多屏幕自适应解决方案。
该属性的作用是决定控件在其父布局中的显示权重,一般用于线性布局中。其值越小,则对应的layout_width或layout_height的优先级就越高,一般横向布局中,决定的是
layout_width
的优先级;纵向布局中,决定的是
layout_height
的优先级。
传统的layout_weight使用方法是将当前控件的layout_width和layout_height都设置成fill_parent,这样就可以把控件的显示比例完全交给layout_weight;这样使用的话,就出现了layout_weight越小,显示比例越大的情况。不过对于2个控件还好,如果控件过多,且显示比例也不相同的时候,控制起来就比较麻烦了,毕竟反比不是那么好确定的。
于是就有了现在最为流行的
0px设值法。看似让人难以理解的layout_height=0px的写法,结合layout_weight,却可以使控件成正比例显示,轻松解决了当前Android开发最为头疼的碎片化问题之一。
先看下面的styles(style_layout.xml)
可以看到,layout_width和layout_height两个属性被我封装成了4个style
根据实际布局情况,选用当中的一种,不需要自己设置,看过我前一个ActivityGroup的Demo的同学应该非常熟悉了
然后我的Demo的布局如下(weight_layout.xml)
整个界面布局看起来非常直观,只是嵌套的逻辑要自己理下。显示效果如下图,其中左面一个是480x800的界面,右面的是320x480的界面(后面的图也如此),可以看出显示比例和代码中完全一致,我就不多说了,大家对照下就能看出来了。
二、自定义尺寸法
这个是我自己想出来的方法,可能是个比较笨的方法,所以没有多少人提过用这种方法解决自适应的问题。虽然这个方法缺点也很多,但有时候也是个不错的方法。
先看下面这张图
可以看到我定义了两套尺寸文件,我们可以看下其中一个文件
这个是
values-480x320
文件夹下
dimens_height.xml
文件中的代码,我把整个高度分成了
80等分,这是因为大部分屏幕的宽度或高度都是80的整数倍(个别特殊的除外),不同的等分在不同的分辨率中设定不同的尺寸值。
由于每一套界面都要写一套,所以有些同学可能觉着不太好,不过这个写起来比较简单,而且以后也不用改,所以有时候也可以考虑用一下!
再看我Demo的布局代码(dimen_layout.xml)
以上是我写的统一的布局代码,来看下在两个不同分辨率的模拟器上的显示效果吧(大家注意我的代码中有margin这样的值也用到了自定义尺寸,如果这个margin使用layout_weight来控制的话,无疑要多嵌套一层线性布局,所以说没有一个方法是十全十美的,这第2个方法有时候用起来反而还要方便一些)
三、在java代码中设置宽高度
也许很多人会反对这种方法,因为即使是官方也是推荐使用xml的方式写布局。不过我们在这不会像Swing那样写那么多麻烦的布局代码,因为我们只是在代码中重新设定控件的宽高度而已,其他属性依然是交给xml布局文件的。这个方法其实是我跟同事偷学来的,虽然我不赞成这样的方法,但他确确实实也是解决屏幕自适应问题的方案之一,而且它没我想象的那么复杂,其实很简单。
首先我们要做的是获取当前屏幕的宽高度,因为这个在后面要用到
我们可以写两个静态变量用来保存当前屏幕的宽高度:
然后在第一个Activity启动的时候,获取这两个值
布局代码我们可以全都统一写成wrap-content,其实写成什么都无所谓,因为这个值只是暂时的
最后我们在Activity的onCreate方法里这么做
大家可以看到其实代码并不复杂,都能看得懂
下面是效果显示图
|
4种Android屏幕自适应解决方案
最新推荐文章于 2024-08-28 03:55:34 发布