API 23中的ContextCompat.getColor崩溃(找不到Context.getColor)



我使用ContextCompat.getColor来获取颜色资源,并对ContextgetColor等不推荐使用的方法具有向后兼容性。

例如:

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

到目前为止,这在我使用过的任何地方都很好,但我在我的应用程序的崩溃日志中看到了很多问题,如下所示:

Caused by java.lang.NoSuchMethodError: No virtual method getColor(I)I in class Landroid/content/Context; or its super classes (declaration of 'android.content.Context' appears in /system/framework/framework.jar)
at android.support.v4.content.ContextCompat.getColor(ContextCompat.java:418)
at com.myapp.MyView.method(MyView.kt:XXX)

看看手机/安卓版本,它们都属于棉花糖系列(6.0-6.1(,我添加了一些关于API检测的日志记录,可以确认它们处于API 23级。

就制造商而言,它们是小米、联想、中兴和OPPO。

到目前为止,我的解决方案是:

int color;
try {
color = ContextCompat.getColor(context, colorRes);
} catch (NoSuchMethodError e) {
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.M) {
// log for a while, to catch if any other versions/devices have issues
Timber.e(
e,
"Couldn't use getColor in API level %s (%s)",
Build.VERSION.SDK_INT,
Build.VERSION.RELEASE
);
}
color = context.getResources().getColor(colorRes);
}
// Now I know color has a value :D

这很好,但还远远不够理想,因为我希望能够透明地使用ContextCompat,而忘记这一点。

我尝试过appcompat版本27.1.028.0.0。有人遇到这个问题吗?有更好的方法来处理它吗?

ContextCompat.getColor()是Support V4库的一部分。

ContextCompat.getColor(YourActivity.this, R.color.my_color)

您需要通过在应用程序build.gradle中添加以下依赖项来添加Support V4库

compile 'com.android.support:support-v4:23.0.1'

希望它能帮助你。

最新更新