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

本文探讨了Android 6.0及以上版本中,旧的getColor方法被弃用的问题,并介绍了新的颜色资源获取方法。针对不同Android版本,新方法提供了兼容性的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近发现看到别人编译代码的时候都是用的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()方法使用:


新的getColor()方法使用:


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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值