Android6.0+解決getColor()方法過時
阿新 • • 發佈:2019-01-06
最近發現看到別人編譯程式碼的時候都是用的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()方法使用:
可能是個人程式碼習慣,就是不願意看到程式碼中有那些過時,警告。。。。。
所以個人還是比較偏向於程式碼潔癖習慣的形成