天天看点

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

最近发现看到别人编译代码的时候都是用的6.0往上的版本,我还在用5.0的,瞬间有点伤感啊,伤感自己不能与时俱进,玻璃心啊,不多说了,今天做一下笔记,关于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()方法使用:

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

新的getColor()方法使用:

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

可能是个人代码习惯,就是不愿意看到代码中有那些过时,警告。。。。。

所以个人还是比较偏向于代码洁癖习惯的形成

继续阅读