- 缩放因子
density
Android实际使用的计算单位是px像素单位,但是我们代码中一般用dp,
所以这里有一个换算的逻辑,可以把这个换算逻辑,简单理解成,一个缩放比例,
那这个比例在哪里可以获取到?可以通过DisplayMetrics.density
获取到
下面举个例子,现在有一台手机,分辨率是:1080x2340
;
DisplayMetrics{density=3.0, width=1080, height=2340, scaledDensity=4.3500004, xdpi=391.885, ydpi=391.026, densityDpi=480, noncompatWidthPixels=1080, noncompatHeightPixels=2340, noncompatDensity=3.0, noncompatDensityDpi=480, noncompatXdpi=391.885, noncompatYdpi=391.026}
它的比例是:3,这个比例的计算逻辑
public void setToDefaults() {
widthPixels = 0;
heightPixels = 0;
density = DENSITY_DEVICE / (float) DENSITY_DEFAULT;
densityDpi = DENSITY_DEVICE;
scaledDensity = density;
xdpi = DENSITY_DEVICE;
ydpi = DENSITY_DEVICE;
noncompatWidthPixels = widthPixels;
noncompatHeightPixels = heightPixels;
noncompatDensity = density;
noncompatDensityDpi = densityDpi;
noncompatScaledDensity = scaledDensity;
noncompatXdpi = xdpi;
noncompatYdpi = ydpi;
}
可以继续看一下源代码
DENSITY_DEVICE
通过不同手机配置获取 adb shell getprop ro.sf.lcd_density
private static int getDeviceDensity() {
// qemu.sf.lcd_density can be used to override ro.sf.lcd_density
// when running in the emulator, allowing for dynamic configurations.
// The reason for this is that ro.sf.lcd_density is write-once and is
// set by the init process when it parses build.prop before anything else.
return SystemProperties.getInt("qemu.sf.lcd_density",
SystemProperties.getInt("ro.sf.lcd_density", DENSITY_DEFAULT));
}
DENSITY_DEFAULT
实际=160
public static final int DENSITY_DEFAULT = DENSITY_MEDIUM;
public static final int `*`DENSITY_MEDIUM`* `= 160;
到这里基本可以看到它的一个换算逻辑了,
- 最小宽度
smallestScreenWidthDp
简称sw
当然还可以通过手机设置页面,查看最小宽度,目前我这台手机的最小宽度=360
,实际宽度=1080
1080/360=3
,最小宽度也可以通过程序获取
Configuration config = getResources().getConfiguration();
int dp = config.smallestScreenWidthDp;
所以实际上我们平时的工作,是把屏幕的物理单位,做了一个映射,比如
1080 映射成 360 了。当然这个映射是可以调节的,比如我们可以在手机设置-显示页面,
调节显示大小,简易模式等。让显示变大变小。底层逻辑就是改变了映射大小。后面就出现了一套设配方案,
sw适配方案。Android 框架是支持这套逻辑的;通过配置 values-sw360 values-sw320
来适配。
- ScreenMatch工具
如果我们需要适配很多的sw,都手动去处理的话,那需要很多工作量,但是可以借助ScreenMatch工具,一次性生成,平时只需要配置默认的sw就可以了
- Overlay
如果是framework/package/app 开发,可以修改源代码,Android 支持通过Overlay 方式,针对不同的设备进行资源覆盖