如何从android包中的资源id获取Drawable对象?
我需要获取一个 Drawable 对象来显示在图像按钮上。有没有办法使用下面的代码(或类似的代码)从 android.R.drawable.* 包中获取对象?
例如如果drawableId是android.R.drawable.ic_delete
mContext.getResources().getDrawable(drawableId)
I need to get a Drawable object to display on an image button. Is there a way to use the code below (or something like it) to get an object from the android.R.drawable.* package?
for example if drawableId was android.R.drawable.ic_delete
mContext.getResources().getDrawable(drawableId)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
从 API 21 开始,您应该使用
getDrawable(int, Theme)
方法而不是getDrawable(int)
,因为它允许您获取与给定屏幕密度/主题的特定资源 ID 关联的可绘制对象。调用已弃用
getDrawable(int)
方法相当于调用getDrawable(int, null)
。您应该使用支持库中的以下代码:
使用此方法相当于调用:
As of API 21, you should use the
getDrawable(int, Theme)
method instead ofgetDrawable(int)
, as it allows you to fetch adrawable
object associated with a particularresource ID
for the givenscreen density/theme
. Calling thedeprecated
getDrawable(int)
method is equivalent to callinggetDrawable(int, null)
.You should use the following code from the support library instead:
Using this method is equivalent to calling:
从 API 21 开始,您还可以使用:
代替 ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
As of API 21, you could also use:
Instead of
ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
从 API 21 开始,`getDrawable(int id)` 已被弃用,
所以现在您需要使用
但最好的方法是:
-
You should create one common class for getting drawable and colors because if in future have any deprecation then you no need to do changes everywhere in your project.You just change in this method
使用此方法,例如:
From API 21 `getDrawable(int id)` is deprecated
So now you need to use
But Best way to do is :
-
You should create one common class for getting drawable and colors because if in future have any deprecation then you no need to do changes everywhere in your project.You just change in this method
use this method like :
最好的方法是
或使用以下代码来绘制左、上、右、下。在这种情况下我设置了drawable left。
并且
getResources().getDrawable()
现已弃用The best way is
OR use the below code for Drawable left, top, right, bottom. I'm setting drawable left in this case.
and
getResources().getDrawable()
is now deprecated遵循 Kotlin 程序员的解决方案(来自 API 22)
Following a solution for Kotlin programmers (from API 22)