我有一个图像资源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);
这段代码已被弃用:
Drawable drawable = getResources().getDrawable( R.drawable.icon );
请使用这个替代:
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
ResourcesCompat.getDrawable(getResources(), R.drawable.icon, null);
(其中第三个参数是可选的Theme实例)。 - vaughandroidgetDrawable(int id)
方法已在API 22中弃用。
相反,您应该使用getDrawable(int id, Resources.Theme theme)
适用于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);
}
getResources().getDrawable(R.drawable.ic_warning_80dp, context?.theme)
请获取资源并使用上下文主题获取可绘制对象。 - Simon Featherstone我只想补充一点,如果在使用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]);
}
这适用于早期和后期Lollipop版本。
无论是矢量图还是其他格式的图像,都可以从矢量资源中获取可绘制对象:
AppCompatResources.getDrawable(context, R.drawable.icon);
注意:
对于矢量图资源,ContextCompat.getDrawable(context, R.drawable.icon);
会产生android.content.res.Resources$NotFoundException
异常。
ivshowing.setBackgroundResource(R.drawable.one);
Drawable drawable = (Drawable) ivshowing.getDrawable();
如果您想从特定视图检索可绘制对象,则最好使用以下代码设置图像。
ivshowing.setImageResource(R.drawable.one);
Drawable drawable = getActivity().getDrawable(R.drawable.icon)
您必须通过兼容的方式获取它,其他方法已被弃用:
Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.my_drawable, null);
binding.floatingActionButton.setImageDrawable(
AppCompatResources.getDrawable(this, android.R.drawable.ic_delete))
当 binding
是根视图并且它引用了 Context
时,你需要进行导入
import androidx.appcompat.content.res.AppCompatResources