如何检查缺少默认值的 android 资源?

How to check for android resources that are missing default values?

我很好奇如何找到缺少默认值的 android 资源。例如,可以在dimens-sw600dp.xml中定义corner_radius,而不在dimens.xml中定义。这会导致最小宽度小于 600 dp 的任何设备运行时崩溃。

在上面的示例中,缺少默认值并不明显。 aapt 运行后,您可以在代码和 xml 中引用维度,尽管缺少默认值。 (通过 R.dimen.corner_radius@dimen/corner_radius)。直到运行时才能发现错误。

Android Studio 包括对缺失翻译的 lint 检查,但似乎不检查其他资源类型。有没有一种简单的方法可以在构建时检查其他缺失的资源(维度、布局等)?

实际上,我找到了一种方法,虽然不是最好的方法,但很管用。

删除所有其他 dimens.xml 文件,主要文件除外(即 v19, w820dp 等)。

之后只需构建您的项目 - 您将获得一个错误列表,其中现在缺少维度。
当您发现问题时,恢复删除即可。

您现在可以依赖 MissingDefaultResource lint 规则(发现 here):

If a resource is only defined in folders with qualifiers like -land or -en, and there is no default declaration in the base folder (layout or values etc), then the app will crash if that resource is accessed on a device where the device is in a configuration missing the given qualifier.

As a special case, drawables do not have to be specified in the base folder; if there is a match in a density folder (such as drawable-mdpi) that image will be used and scaled. Note however that if you only specify a drawable in a folder like drawable-en-hdpi, the app will crash in non-English locales.

There may be scenarios where you have a resource, such as a -fr drawable, which is only referenced from some other resource with the same qualifiers (such as a -fr style), which itself has safe fallbacks. However, this still makes it possible for somebody to accidentally reference the drawable and crash, so it is safer to create a default dummy fallback in the base folder. Alternatively, you can suppress the issue by adding tools:ignore="MissingDefaultResource" on the element.

(This scenario frequently happens with string translations, where you might delete code and the corresponding resources, but forget to delete a translation. There is a dedicated issue id for that scenario, with the id ExtraTranslation.)

使缓存无效并重新启动应该可以解决问题 检查清除文件系统缓存