Android 6.0即API 23中 已經過時的替代方法隨手記錄

最近在使用這些方法的時候總是在網上搜,感覺很麻煩,所以在這裏記憶一下。

getResources().getDrawable() 過時的解決方法:

1. 當你這個Drawable不受主題影響時

ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);

2.當你這個Drawable受當前Activity主題的影響時

ContextCompat.getDrawable(getActivity(), R.drawable.name);

3.當你這個Drawable想使用另外一個主題樣式時

ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);

 getColor()方法過時解決方案:

開發過程中遇到getColor()方法過時,Google給出的解決方案是:使用ContextCompat.getColor(context, R.color.color);

ContextCompat.getColor(context, R.color.colorPrimary);
//源碼如下:
 public static final int getColor(Context context, int id) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 23) {
            return ContextCompatApi23.getColor(context, id);
        } else {
            return context.getResources().getColor(id);
        }
    }

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章