前言
在Android 高版本上使用getDrawable(int id)时,如下,有提示使用的这个方法废弃了
- mIvAlbum.setBackground(getResources().getDrawable(R.drawable.music_album_unknown));
点进入源码查有提示我们使用新的方法getDrawable(int, Theme)
- /*
- * ......
- * @see #getDrawable(int, Theme)
- * @deprecated Use {@link #getDrawable(int, Theme)} instead.
- */
- @Deprecated
- public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
- final Drawable d = getDrawable(id, null);
- if (d != null && d.canApplyTheme()) {
- Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme "
- + "attributes! Consider using Resources.getDrawable(int, Theme) or "
- + "Context.getDrawable(int).", new RuntimeException());
- }
- return d;
- }
总结
虽然getDrawable(int id)已经废弃了,但是依旧还是可以用的。
如果你的Android版本比较高,那就按照官方的提示,可以使用getDrawable(int, Theme)替代。
正文
- 使用drawable资源但不为其设置theme主题
- ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
- 使用默认的activity主题
- ContextCompat.getDrawable(getActivity(), R.drawable.name);
- 使用自定义主题
- ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);
推荐使用
为了兼容,可以使用如下
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
参考文章
© 版权声明