Resources.NotFoundException 仅在某些设备上

Resources.NotFoundException only on some devices

我正在获取这样的颜色,对于我在崩溃报告中看到的一些设备,它返回 0。他们都在 res/values/colors.xml。前任。 <color name="firstcolor">#A8A77A</color>colorString 是动态的。

int primaryColor = ContextCompat.getColor(context,
            context.getResources().getIdentifier(colorString.toLowerCase(),
                    context.getString(R.string.color), context.getPackageName()));

我已经在这些设备上进行了测试并且有效: LG G5 (7.0) - 诺基亚 N1 (5.1.1) - 摩托罗拉 G (5.1) - 三星 Core Prime (4.4.4)

崩溃报告来自: 三星 Ace 4 (4.4.2) - 索尼 Xperia M5 E5603 (6.0) - NG 嫉妒 (4.4.2)

Fatal Exception: android.content.res.Resources$NotFoundException: Resource ID #0x0
   at android.content.res.Resources.getValue(Resources.java:1133)
   at android.content.res.Resources.getColor(Resources.java:815)
   at android.support.v4.content.ContextCompat.getColor(ContextCompat.java:434)

有什么方法可以找出为什么它不适用于其中一些设备?

尝试清理项目并查看

也就是用

ContextCompat.getColor(context,R.color.firstcolor)

你可以这样使用,你应该在getIdentifier中defType为color

int resourceId = getResources().getIdentifier(colorString.toLowerCase(), "color", context.getPackageName());

int primaryColor = ContextCompat.getColor(resourceId);

原来是 toLowerCase() 的问题。对于某些语言环境,大写 I 被转换为 ı 而不是 i,这导致无法通过标识符找到资源。