Android:ContextCompat.getColor(上下文,R.color.my_color),无法解析 "getColor"

Android: ContextCompat.getColor(context, R.color.my_color), cannot resolve "getColor"

我知道这里有人问过几个类似的问题,但是 none 的解决方案对我有用。

我刚刚将我的应用程序从 Ecilpse(juno) 转移到 Android Studio 1.5.1;从 API 19 到 API 23(compileSdkVersion).

目前我遇到这个错误 "getResources().getColor(R.color.my_color)" 已贬值且无法使用。

在网上搜索后,尝试用"ContextCompat.getColor(context, R.color.my_color)"代替。错误在于 "getColor" 部分,因为它说无法解决:

方法 "ContextCompat" 但是允许我使用 "getDrawable"、"getExternalCacheDirs"、"getExternalFilesDirs" 和 "getObbDirs"; 除了"getColor"

我还确保我的应用程序中有这两个 build.gradle(依赖项{}):

下面是我为此 class (DetailsActivity) 导入的内容:

另外,除了"ContextCompat",我也尝试过使用"ResourcesCompat";但它仍然对我不起作用。

我仍然是 Android 开发的初学者,从事学校项目。 任何人都可以就我做错了什么提出一些建议并指出正确的方向吗?提前致谢!

如果您使用大于 24 的 API 级别进行编译,则不必在那里使用 ContextCompat,因为这只是早期版本的兼容性功能。您还可以使用 Context.getColor() But notice the method signature! If you just want a color in the default theme you only have to provide the int value of its reference: http://developer.android.com/reference/android/content/Context.html#getColor(int)

您目前正在尝试使用两个参数(颜色和主题)访问 getColor(),但由于没有支持这些参数的方法,因此无法在那里工作。如果您删除第二个参数,您当前的解决方案将起作用。 但直接使用 Context 或 Resources 并在不需要时删除 v4 Appcompat 引用会更方便。

你可以使用这个方法。

这是支持库中的 ContextCompat Developer Link

public static final int getColor(Context context, int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 23) {
        return ContextCompat.getColor(context, id);
    } else { 
        return context.getResources().getColor(id);
    } 
} 

使用此方法前,首先要在build.gradle脚本中添加依赖。具体如下:

dependencies {
    // other stuff here
    compile 'com.android.support:support-v4:23.0.0'
}