前言

在Android 高版本上使用getDrawable(int id)时,如下,有提示使用的这个方法废弃了

  1. mIvAlbum.setBackground(getResources().getDrawable(R.drawable.music_album_unknown));
复制

点进入源码查有提示我们使用新的方法getDrawable(int, Theme)

  1. /*
  2. * ......
  3. * @see #getDrawable(int, Theme)
  4. * @deprecated Use {@link #getDrawable(int, Theme)} instead.
  5. */
  6. @Deprecated
  7. public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
  8. final Drawable d = getDrawable(id, null);
  9. if (d != null && d.canApplyTheme()) {
  10. Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme "
  11. + "attributes! Consider using Resources.getDrawable(int, Theme) or "
  12. + "Context.getDrawable(int).", new RuntimeException());
  13. }
  14. return d;
  15. }
复制

总结

虽然getDrawable(int id)已经废弃了,但是依旧还是可以用的。

如果你的Android版本比较高,那就按照官方的提示,可以使用getDrawable(int, Theme)替代。

正文

  1. 使用drawable资源但不为其设置theme主题
  1. ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
复制
  1. 使用默认的activity主题
  1. ContextCompat.getDrawable(getActivity(), R.drawable.name);
复制
  1. 使用自定义主题
  1. ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);
  2.  
复制

推荐使用

为了兼容,可以使用如下

  1. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  2. return resources.getDrawable(id, context.getTheme());
  3. } else {
  4. return resources.getDrawable(id);
  5. }
复制

参考文章

  1. Context#getResources().getDrawable()方法过时后的替代方法
  2. Android getResources().getDrawable() deprecated API 22

相关文章

暂无评论

none
暂无评论...