如何从资源创建Drawable

Use*_*337 272 android drawable

我有一个图像res/drawable/test.png(R.drawable.test).
我想将此图像传递给接受的函数Drawable.
(例如mButton.setCompoundDrawables())

那么如何将图像资源转换为Drawable

Jem*_*ems 548

您的Activity应该具有getResources方法.做:

Drawable myIcon = getResources().getDrawable( R.drawable.icon );
Run Code Online (Sandbox Code Playgroud)

  • 从API版本21开始,不推荐使用此方法,您应将其替换为:Drawable drawable = ResourcesCompat.getDrawable(getResources(),page.getImageId(),null); (45认同)
  • @Boren与使用ContextCompat.getDrawable(this,R.drawable.icon)相同;? (3认同)
  • 如果您使用的是可绘制矢量,请不要使用此功能。请改用AppCompatResources.getDrawable(context,R.drawable.icon)。 (3认同)
  • 如果您碰巧想要在 Activity 类之外使用它,则必须找到其他方法来访问 getResources() 所在的上下文;[此答案建议将其传递给构造函数](http://stackoverflow.com/a/6214567/404960) (2认同)
  • 如果R.drawable.icon是Vector可绘制对象,以上建议似乎都不起作用。 (2认同)

dan*_*kas 130

不推荐使用此代码:

Drawable drawable = getResources().getDrawable( R.drawable.icon );
Run Code Online (Sandbox Code Playgroud)

请改用:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这将应用给定上下文中的主题.如果要确保不使用主题,可以使用`ResourcesCompat.getDrawable(getResources(),R.drawable.icon,null);`(其中第3个param是可选的Theme实例). (11认同)

Chr*_*ell 23

getDrawable (int id)方法从API 22开始折旧.

相反,你应该使用getDrawable (int id, Resources.Theme theme)for API 21+

代码看起来像这样.

Drawable myDrawable;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    myDrawable = context.getResources().getDrawable(id, context.getTheme());
} else {
    myDrawable = context.getResources().getDrawable(id);
}
Run Code Online (Sandbox Code Playgroud)


小智 13

我想补充一点,如果在使用getDrawable(...)时收到"已弃用"消息,则应使用支持库中的以下方法.

ContextCompat.getDrawable(getContext(),R.drawable.[name])
Run Code Online (Sandbox Code Playgroud)

使用此方法时,您不必使用getResources().

这相当于做类似的事情

Drawable mDrawable;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    mDrawable = ContextCompat.getDrawable(getContext(),R.drawable.[name]);
} else {
    mDrawable = getResources().getDrawable(R.id.[name]);
}
Run Code Online (Sandbox Code Playgroud)

这适用于Lollipop前后版本.


Dha*_*tel 5

从向量资源获取 Drawable,无论其是否为向量:

AppCompatResources.getDrawable(context, R.drawable.icon);
Run Code Online (Sandbox Code Playgroud)

注意:
ContextCompat.getDrawable(context, R.drawable.icon);将为android.content.res.Resources$NotFoundException矢量资源生成。