资源。getColor(int id)方法已弃用。

@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException {
    return getColor(id, null);
}

我该怎么办?


当前回答

我不想仅为getColor包含支持库,因此我使用类似于

public static int getColorWrapper(Context context, int id) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return context.getColor(id);
    } else {
        //noinspection deprecation
        return context.getResources().getColor(id);
    }
}

我想代码应该可以正常工作,并且已弃用的getColor不能从API < 23中消失。

这是我在Kotlin中使用的:

/**
 * Returns a color associated with a particular resource ID.
 *
 * Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor].
 */
@Suppress("DEPRECATION")
@ColorInt
fun getColorHelper(context: Context, @ColorRes id: Int) =
    if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);

其他回答

对于所有的Kotlin用户:

context?.let {
    val color = ContextCompat.getColor(it, R.color.colorPrimary)
    // ...
}

最好的等效方法是使用ContextCompat。getColor和ResourcesCompat。色鬼。我做了一些扩展函数用于快速迁移:

@ColorInt
fun Context.getColorCompat(@ColorRes colorRes: Int) = ContextCompat.getColor(this, colorRes)

@ColorInt
fun Fragment.getColorCompat(@ColorRes colorRes: Int) = activity!!.getColorCompat(colorRes)

@ColorInt
fun Resources.getColorCompat(@ColorRes colorRes: Int) = ResourcesCompat.getColor(this, colorRes, null)

使用Android支持库中的ResourcesCompat的getColor(Resources, int, Theme)方法。

int white = ResourcesCompat.getColor(getResources(), R.color.white, null);

我认为它比ContextCompat的getColor(Context, int)更好地反映了您的问题,因为您询问了资源。在API级别23之前,主题将不会被应用,方法将调用getColor(int),但您将不会看到已弃用的警告。主题也可以为空。

getColor(int):此方法在API级别23中已弃用。 使用getColor(int, android.content.res.Resources.Theme)代替。

我尝试minSDK = 21:

if(Build.VERSION.SDK_INT < 23) {
                resources.getColor(R.color.rippelColor, null)
            } else {
                resources.getColor(R.color.rippelColor)
            }

来自developer.android.com的官方参考

我也很沮丧。我的需求非常直截了当。我想要的只是资源中的ARGB颜色,所以我写了一个简单的静态方法。

protected static int getARGBColor(Context c, int resId)
        throws Resources.NotFoundException {

    TypedValue color = new TypedValue();
    try {
        c.getResources().getValue(resId, color, true);
    }
    catch (Resources.NotFoundException e) {
        throw(new Resources.NotFoundException(
                  String.format("Failed to find color for resourse id 0x%08x",
                                resId)));
    }
    if (color.type != TYPE_INT_COLOR_ARGB8) {
        throw(new Resources.NotFoundException(
                  String.format(
                      "Resourse id 0x%08x is of type 0x%02d. Expected TYPE_INT_COLOR_ARGB8",
                      resId, color.type))
        );
    }
    return color.data;
}