【发布时间】:2011-06-16 15:06:50
【问题描述】:
我有一张图片 res/drawable/test.png (R.drawable.test)。
我想将此图像传递给接受Drawable 的函数,例如mButton.setCompoundDrawables().
那么如何将图像资源转换为Drawable?
【问题讨论】:
我有一张图片 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);(其中第三个参数是可选的主题实例)。
getDrawable (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)
我想补充一点,如果您在使用 getDrawable(...) 时收到“已弃用”消息,您应该使用支持库中的以下方法。
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 前后版本。
【讨论】:
无论是否为矢量,都从矢量资源中获取 Drawable:
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 = (Drawable) ivshowing.getDrawable();
因此,如果您想从特定视图中检索可绘制对象,最好使用以下代码设置图像。
ivshowing.setImageResource(R.drawable.one);
只有这样我们才能准确转换drawable。
【讨论】:
如果你是从片段继承的,你可以这样做:
Drawable drawable = getActivity().getDrawable(R.drawable.icon)
【讨论】:
您必须通过兼容的方式获取它,不推荐使用其他方式:
Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.my_drawable, null);
【讨论】: