Android6.0+解决getColor()方法过时

关于getResources().getColor()方法过时的替代方法,在Android的6.0以上的编译环境中getColor方法过时了,也就是说以后不建议用这种方式,如果一个方法过时了,应该会有另一种方法来顶替的,接下来就来看看代码吧

getColor()过时过时的源码:

 /**
     * Returns a color integer associated with a particular resource ID. If the
     * resource holds a complex {@link ColorStateList}, then the default color
     * from the set is returned.
     *
     * @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.
     *
     * @throws NotFoundException Throws NotFoundException if the given ID does
     *         not exist.
     *
     * @return A single color value in the form 0xAARRGGBB.
     * @deprecated Use {@link #getColor(int, Theme)} instead.
     */
    @ColorInt
    @Deprecated
    public int getColor(@ColorRes int id) throws NotFoundException {
        return getColor(id, null);
    }

新替代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);
        }
    }

在新的方法中进行了判断,进行6.0系统的区分,针对于6.0以下还是调用了原来的getColor方法,对于6.0+的使用了新的方法进行替代,这个就不用说了吧,一般的升级都会对老版本进行兼容,具体的使用方法也稍有变化

过时getColor()方法使用:

new TextView(this).setTextColor(getResources().getColor(R.color.white));

新的getColor()方法使用:

new TextView(this).setTextColor(ContextCompat.getColor(this, R.color.white));

最后总结

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
           new TextView(this).setTextColor(ContextCompat.getColor(this, R.color.white));
        } else {
           new TextView(this).setTextColor(getResources().getColor(R.color.white));
        }

猜你喜欢

转载自blog.csdn.net/fengyeNom1/article/details/81237543