一、前言
Android设备的碎片化,确实让开发者很头疼。Android设备成千上万,每台设备硬件设备各不相同。有的卖高价低配,有的卖低价高配,这里就不发表其他言论了。聊回正题,每台不同的Android设备,屏幕参数都有差异,主要的参数有三种:屏幕尺寸、屏幕分辨率、屏幕像素密度。
屏幕尺寸:即屏幕的物理尺寸
1英寸(inch)=2.54厘米(cm)
屏幕分辨率:即屏幕上显示的像素个数,屏幕尺寸一样的情况下,分辨率越高,
显示效果就越精细和细腻。
屏幕像素密度:即没英寸屏幕所拥有的像素数,像素密度越大,显示效果越精细和细腻。
像素密度=√{(长度像素数^2+宽度像素数^2)}/ 屏幕尺寸
Density-independent pixel (dp)独立像素密度。标准是160dip.即1dp对应1个pixel,
计算公式如:px = dp * (dpi / 160),屏幕密度越大,1dp对应 的像素点越多。
上面的公式中有个dpi,dpi为DPI是Dots Per Inch(每英寸所打印的点数),
也就是当设备的dpi为160的时候1px=1dp;
了解完这些的话,基本上就知道什么叫坑了。
二、谷歌对适配提供的方案
- PercentLayout
- dp
- ……
dp用鸿洋大神一句话的概括就是
dp能够让同一数值在不同的分辨率展示出大致相同的尺寸大小。但是当设备的尺寸差异较大的时候,就无能为力了
三、AutoLayout
先放上AutoLayout的项目地址:Github仓库链接
使用上,先设定设计图的大小,然后就是在布局中用px作为尺寸单位,就能在不同分辨率,不同尺寸和不同像素密度的屏幕上显示差异不大的效果。
因为AutoLayout已经停止维护了,不过看到该项目folk的数量还是挺多的。为了以后使用的便利,特意folk了一把,进行扩展。
clone下来后,在build项目的过程中,你可能首先把gradle的版本升成最新的,但是接下来你会一道一堆一连贯的错误。
1. Unable to load class ‘org.gradle.api.internal.artifacts.ImmutableModuleIdentifierFactory’
百度无果后,在android-maven-gradle-plugin的github仓库的issues中找到了问题所在,具体看下图
也就是
Error:Unable to load class ‘org.gradle.api.internal.artifacts.ImmutableModuleIdentifierFactory’.
Possible causes for this unexpected error include:
- Gradle’s dependency cache may be corrupt (this sometimes occurs after a network connection timeout.) Re-download dependencies and sync project (requires network)
- The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem. Stop Gradle build processes (requires restart)
- Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.
百度无果后,在android-maven-gradle-plugin的github仓库的issues中找到了问题所在,具体看下图
说明该插件的版本是与Gradle的版本对应的,而且在Gradle2.4之后,依赖的名称就变了,多了个gradle,此处我用的是Gradle2.3.3,所以使用com.github.dcendents:android-maven-gradle-plugin:1.4.1
2. Failed to resolve:com.android.support:*
这里我有个强迫症会把buildtool的版本升为最新(26.0.2),接着把下面的依赖也全改为26.0.2的,然后就出现错误。
这个问题在stackoverflow上找到了答案,在Project的build.gradle中修改为
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
3. cannot resolve R.styleable.Theme和R.styleable.Theme_actionBarTheme
对于这种情况,经过查阅https://developer.android.com,大概可以猜到,应该是修改了buildtools后出现的问题,Theme应该是旧版本才有的,Theme_actionBarTheme也一样。
所以,直接查找在android.support.v7.appcompat包中的R.styleable。可以找到R.styleable.AppCompatTheme,搜索一些actionBarTheme,可以找到对应的R.styleable.AppCompatTheme_actionBarTheme,替换进去即可,具体修改如下
R.styleable.AppCompatTheme —> R.styleable.AppCompatTheme
R.styleable.Theme_actionBarTheme —> R.styleable.AppCompatTheme_actionBarTheme