何时使用ContextCompat类

问题描述 投票:12回答:3

我想知道何时在应用程序中使用ContextCompact类。基本上它用于何时使用它?我读过开发者网站,它说ContextCompact是“帮助访问Context中的功能”。但这条线意味着什么?

android
3个回答
10
投票

ContextCompat是一个用基础上下文替换一些工作的类。

例如,如果您之前使用过类似的东西

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

现在它自Android 6.0(API 22+)以来已被弃用,所以你应该使用:

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

或者使用填充主题的ContextCompat取决于你的Context的主题:

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

getDrawable相同

此外,ContextCompat还包含API 22+功能的其他方法,例如检查权限或向堆栈添加多个活动


7
投票

当您想要检索资源时使用ContextCompat类,例如drawable或color,而不用担心主题。它为访问资源提供统一的接口,并提供向后兼容性。

常见用例可以是颜色或可绘制等,例如..

ContextCompat.getDrawable(context,R.drawable.someimage)); ContextCompat.getDrawable(context,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'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);
    }
}

此方法负责API级别解析并自动解决状态或主题。 23以上,可以访问颜色状态,这是内部为您解决的,而您应该检查每个资源。


1
投票

基本上根据官方开发者网站,它是一个Helper,用于以向后兼容的方式访问API级别4之后引入的Context中的功能。

您可以查看此链接以获取更多详细信息。 https://developer.android.com/reference/android/support/v4/content/ContextCompat.html

基本上不推荐使用getBackgroundResource或getColor方法,并使用ContextCompact作为替代方法。我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.