相关单位
我们常用的资源单位有px、dp、sp、dpi,如图:

补充
发现有些视觉同学可能不大清楚开发要的视觉标注中 dp 和 px 的区别。这边说下,
px 是指像素,比如车机的物理尺寸为[1920, 720]px,像素密度为 160dpi,像素密度(dpi)为单位面积的像素数。
而 dp 是指密度无关像素(开发在代码中需要使用到的单位),我们规定在中密度(mdpi:~160dpi)的屏幕上 1dp = 1px。因此如果某个屏幕的像素密度为 480dpi,那么在这个屏幕上 1dp = 480/160 px = 3px。
但我们车机是 160dpi ,因此其 1dp = 1px。
所以在输出车机的视觉标注时,直接输出 [1920, 720]dp 的标注就行。

Context
我们知道 Context 提供访问应用独有资源的接口,如图:

但从 android R 之后只能从 Activity 或者 WindowContext 来访问资源(在多窗口模式下仅这其它 Context 获取的 Configuration 可能错误)。

如需要在主屏幕上添加应用覆盖的窗口,需要用 Window Context 来 inflate view 和添加 window 到 WindowManager 以便在多窗口模式下也能获取到正确的资源:
final DisplayManager dm = anyContext.getSystemServer(DisplayManager.class);
final Display primaryDisplay = dm.getDisplay(DEFAULT_DISPLAY);
final Context windowContext = anyContext.createDisplayContext(primaryDisplay);
final View overlayView = Inflater.from(windowContext).inflate(layoutXml, null);
// WindowManager.LayoutParams initialization
...
mParams.type = TYPE_APPLICATION_OVERLAY;
...
mWindowContext.getSystemService(WindowManager.class).addView(overlayView, mParams);
Resources、Configurations、Assets
通过 Context 来到 Resources 后,我们会通过 Resources 拿到 AssetManager 去查找资源,那 Resources、Configuration、Assets 分别是什么呢?

查询逻辑
以查找 dimens 资源为例,其流程如下:

简单来说分为三步:

解析文件目录
解析顺序和流程如下:

查找最优文件目录
顺序和流程如下:

参考:
Google Design Documentation
Google 官方:屏幕兼容性
原创文章,欢迎转载,但请注明出处
网友评论