【问题标题】:When to use ContextCompat class何时使用 ContextCompat 类
【发布时间】:2017-03-29 07:31:34
【问题描述】:

我想知道何时在应用程序中使用ContextCompact 类。基本上它的用途是什么以及何时使用它?我读过开发者网站,上面写着ContextCompact 是“在上下文中访问功能的助手”。但是这条线是什么意思呢?

【问题讨论】:

标签: android


【解决方案1】:

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+ 功能的方法,例如检查权限或向堆栈添加多个活动

【讨论】:

  • 什么是getContext()?它告诉我Unresolved reference: getContext
  • getContext() 是 Fragment 中的一个方法,例如。如果你从 Activity 调用它,那么写 this 就足够了
【解决方案2】:

ContextCompat 类用于当您想要检索资源(例如可绘制或颜色)而不用担心主题时。它提供统一的资源访问接口并提供向后兼容性。

常见的用例可能是获取颜色或可绘制等,例如..

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,颜色状态是可访问的,这是内部为您解决的,而不是您应该为每个资源检查它。

【讨论】:

    【解决方案3】:

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

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

    基本上不推荐使用 getBackgroundResource 或 getColor 方法,而使用 ContextCompact 是一种替代方法。我希望这有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2016-04-09
      • 2016-11-08
      • 1970-01-01
      • 2018-11-11
      • 2012-05-02
      • 1970-01-01
      相关资源
      最近更新 更多