今天,簡單講講android裡如何解決getColor()方法過時的問題。
之前,我寫部落格講了程式員需要解決過時的方法的問題,Google會提供過時函數的替代函數,程式員有責任找到替代函數,并且解決過時的函數。是以,我檢測代碼時發現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()方法使用:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2QvwVe0lmdhJ3ZvwFM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2Lc1TP35EejpWYzJESiZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DNwMzN0YDNxEjNwcDM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
新的getColor()方法使用:
這裡還提一下getDrawable過時的替代方法,基本是一樣的。
用getDrawable()方法過時了
現象
網友推薦
谷歌查詢結果
android 解決getColor()方法過時就講完了。
就這麼簡單。