I want to know when to use ContextCompact
class in an application. Basically what is it used for and when to use it? I have read developers site, it says Cont
ContextCompat class is used when you would like to retrieve resources, such as drawable or color without bother about theme. It provide uniform interface to access resources and provides backward compatibility.
Common use case could be get color or drawable etc e.g..
ContextCompat.getDrawable(context, R.drawable.someimage)); ContextCompat.getDrawable(context, R.color.blue));
Lets see the source code of getColor()
/*
* Returns a color associated with a particular resource ID
*
* 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.
*/
@ColorInt
public static final int getColor(Context context, @ColorRes int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 23) {
return ContextCompatApi23.getColor(context, id);
} else {
return context.getResources().getColor(id);
}
}
this method takes care the API level resolution and resolve states or theme automatically. Above 23, the color states are accessible, which is internally resolved for you, instead you should check it for each resource.