一、前言:
Android用ContextCompat替换getResources()获取资源; android SDK 升级到 23 之后,getResource.getColor(R.color.color_name) 过时, 可以使用新加入的方法 ContextCompat.getColor(context, R.color.color_name) 。
SDK 升级到 23 之后,Context类已经提供了getColor(int id)等一系列获取资源文件的方法。
ContextCompat.getDrawable
ContextCompat.getColor
替代:
context.getResources().getDrawable
context.getResources().getColor
源码:
@ColorInt
public static int getColor(@NonNull Context context, @ColorRes int id) {
if (Build.VERSION.SDK_INT >= 23) {
return context.getColor(id);
} else {
return context.getResources().getColor(id);
}
}
二、使用:
ContextCompat 可以理解为是封装了 Context 的一些便捷方法,如加载图片等资源文件,它在源码中的位置如下所示:

1、检查权限
//动态检查相机权限
int selfPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
//检查结果
if (selfPermission == PackageManager.PERMISSION_GRANTED) {
//有许可
} else {
//无
}
2、获取应用程序代码缓存文件的目录
2.1 缓存文件系统设计中的缓存路径
//缓存文件的目录的路径
File codeCacheDir = ContextCompat.getCodeCacheDir(this);
2.2 获取 应用程序的私有文件的目录
返回文件系统上所有属于这个应用程序的私有文件的目录的绝对路径。应用程序不应该直接使用这个路径,而应该使用 Context # getfiledir ()、 Context # getcachedir ()、 Context # getdir (String,int)或其他 Context 上的存储 api
//获取 应用程序的私有文件的目录的绝对路径。
File dataDir = ContextCompat.getDataDir(this);
2.3 外部存储设备上应用程序特定目录
这里返回的外部存储设备被认为是设备的永久部分,包括模拟的外部存,
//外部存储设备上应用程序特定目录
File[] cacheDirs = ContextCompat.getExternalCacheDirs(this);
3、加载Color资源文件
//加载资源ID
int color = ContextCompat.getColor(this,R.color.purple_200);

4、加载Drawable资源文件
//加载 Drawable
Drawable drawable = ContextCompat.getDrawable(this,R.drawable.bg_bottom_tips_shape);

网友评论