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

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


你的Activity应该有getResources方法。做的事:

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


在API版本21中,此方法已弃用,可以用以下方法替代:

Drawable myIcon = AppCompatResources.getDrawable(context, R.drawable.icon);

如果你需要指定一个自定义主题,下面将应用它,但仅当API版本为21或更高:

Drawable myIcon =  ResourcesCompat.getDrawable(getResources(), R.drawable.icon, theme);

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

ivshowing.setBackgroundResource(R.drawable.one);

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

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

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

 ivshowing.setImageResource(R.drawable.one);

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

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);

我只是想补充一点,如果你在使用getDrawable(…)时得到“deprecated”消息,你应该使用支持库中的以下方法。

ContextCompat.getDrawable(getContext(),R.drawable.[name])

在使用此方法时,您不必使用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]);
}

这适用于前和后棒棒糖版本。

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

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

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

如果你从一个片段继承,你可以这样做:

可绘制可绘制= getActivity().getDrawable(R.drawable.icon)

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

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

在Kotlin中,你可以这样做:

binding.floatingActionButton.setImageDrawable(
            AppCompatResources.getDrawable(this, android.R.drawable.ic_delete))

其中绑定是根视图,这是指上下文,你需要导入

import androidx.appcompat.content.res.AppCompatResources