博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android getResources().getDrawable() deprecated API 22
阅读量:4122 次
发布时间:2019-05-25

本文共 2239 字,大约阅读时间需要 7 分钟。

以下解决方法摘自 stackoverflow , 点击下方链接可跳转

No.1

You have some options to handle this deprecation the right (and future proof) way, depending on which kind of drawable you are loading:

  • A) drawables with theme attributes
ContextCompat.getDrawable(getActivity(), R.drawable.name);

You’ll obtain a styled Drawable as your Activity theme instructs. This is probably what you need.

* B) drawables without theme attributes

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

You’ll get your unstyled drawable the old way.

EXTRA) drawables with theme attributes from another theme

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

Explanation:

API 21 (Android 5.0 Lollipop) introduced some new theme attributes such as android:colorAccent that modify the appearance of drawables that hold references to those new theme attributes values.The AppCompat library handles pre and post-Lollipop drawable styling for you.

If you do use the deprecated getDrawable() method to obtain a drawable resource with theme attributes, you will get a partially-styled drawable and a logcat warning.You can see this in API 22 android.content.res.Resources source code:

@Deprecated@Nullablepublic Drawable getDrawable(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;}

No.2

You should use the following code from the support library instead:

ContextCompat.getDrawable(context, R.drawable.***)

Using this method is equivalent to calling:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {    return resources.getDrawable(id, context.getTheme());} else {    return resources.getDrawable(id);}

As of API 21, you should use the getDrawable(int, Theme) method instead of getDrawable(int), as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int) method is equivalent to calling getDrawable(int, null).

转载地址:http://dvvpi.baihongyu.com/

你可能感兴趣的文章
String s1 = new String("abc"); String s2 = ("abc");
查看>>
JAVA数据类型
查看>>
Xshell 4 入门
查看>>
SoapUI-入门
查看>>
Oracle -常用命令
查看>>
JAVA技术简称
查看>>
ORACLE模糊查询优化浅谈
查看>>
2017——新的开始,加油!
查看>>
【Python】学习笔记——-6.2、使用第三方模块
查看>>
【Python】学习笔记——-7.0、面向对象编程
查看>>
【Python】学习笔记——-7.2、访问限制
查看>>
【Python】学习笔记——-7.3、继承和多态
查看>>
【Python】学习笔记——-7.5、实例属性和类属性
查看>>
Linux设备模型(总线、设备、驱动程序和类)之四:class_register
查看>>
git中文安装教程
查看>>
虚拟机 CentOS7/RedHat7/OracleLinux7 配置静态IP地址 Ping 物理机和互联网
查看>>
弱类型、强类型、动态类型、静态类型语言的区别是什么?
查看>>
Struts2技术内幕图书 转载
查看>>
Java异常分类
查看>>
项目中的jackson与json-lib使用比较
查看>>