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

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


当前回答

此代码已弃用:

Drawable drawable = getResources().getDrawable( R.drawable.icon );

用这个代替:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);

其他回答

从vector资源中获取Drawable,不管它是否是vector:

AppCompatResources.getDrawable(context, R.drawable.icon);

注意: ContextCompat。getDrawable(上下文,R.drawable.icon);将生成android.content.res。vector资源$NotFoundException

你必须通过兼容的方式获得它,其他的不推荐:

Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.my_drawable, null);

getDrawable (int id)方法自API 22起已弃用。

相反,你应该使用getDrawable (int id, Resources。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);
}

此代码已弃用:

Drawable drawable = getResources().getDrawable( R.drawable.icon );

用这个代替:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);

如果你试图从图像设置为的视图中获取可绘制对象,

ivshowing.setBackgroundResource(R.drawable.one);

然后drawable将只返回空值,代码如下…

   Drawable drawable = (Drawable) ivshowing.getDrawable();

最好用下面的代码来设置图像,如果你想从一个特定的视图中检索drawable。

 ivshowing.setImageResource(R.drawable.one);

只有这样,我们才能精确地转换可绘制对象。