原来写法:
tv.setTextColor(R.color.green);
发现颜色不对,修改后:
tv.setTextColor(ContextCompat.getColor(context, R.color.green));
原因:
getColor(int id)在API版本23时(Android 6.0)已然过时,使用ContextCompat.getColor(Context context, int id);同时兼容高、低版本。
源码解析:
/**
* Returns a color associated with a particular resource ID
* <p>
* Starting in {@link android.os.Build.VERSION_CODES#M}, the returned
* color will be styled for the specified Context's theme.
*
* @param id The desired resource identifier, as generated by the aapt
* tool. This integer encodes the package, type, and resource
* entry. The value 0 is an invalid identifier.
* @return A single color value in the form 0xAARRGGBB.
* @throws android.content.res.Resources.NotFoundException if the given ID
* does not exist.
*/
public static final int getColor(Context context, int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 23) {
return ContextCompatApi23.getColor(context, id);
} else {
return context.getResources().getColor(id);
}
}
继续查看ContextCompatApi23.getColor(context, id)源码:
public static int getColor(Context context, int id) {
return context.getColor(id);
}
继续context.getColor(id)源码:
/**
* Returns a color associated with a particular resource ID and styled for
* the current theme.
*
* @param id The desired resource identifier, as generated by the aapt
* tool. This integer encodes the package, type, and resource
* entry. The value 0 is an invalid identifier.
* @return A single color value in the form 0xAARRGGBB.
* @throws android.content.res.Resources.NotFoundException if the given ID
* does not exist.
*/
@Nullable
public final int getColor(int id) {
return getResources().getColor(id, getTheme());
}