When to use the ContextCompact class

I want to know when to use the ContextCompact class in an application. Basically, what is its use and when to use it? I read the developer site, he says ContextCompact is a "helper for accessing functions in Context". But what does this line mean?

+4
source share
3 answers

ContextCompat is a class for replacing some work with a basic context.

For example, if you used before something like

getContext().getColor(R.color.black);

Now its obsolete since android 6.0 (API 22+), so you should use:

getContext().getColor(R.color.black,theme);

or use ContextCompatthat automatically fills the topic, depending on the topic Context:

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

Same thing with getDrawable

ContextCompat API 22+,

+4

ContextCompat , , , . .

.., .

ContextCompat.getDrawable(, R.drawable.someimage)); ContextCompat.getDrawable(, R.color.blue));

getColor()

/*
 * 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 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);
    }
}

API . 23, , , .

+3

, Context, API 4 .

. https://developer.android.com/reference/android/support/v4/content/ContextCompat.html

getBackgroundResource getColor , ContextCompact . , .

+1

Source: https://habr.com/ru/post/1673475/


All Articles