我有一个图像 res/drawable/test.png (R.drawable.test) .我想将此图像传递给接受 Drawable 的函数 .(例如mButton.setCompoundDrawables())
res/drawable/test.png
Drawable
那么如何将图像资源转换为 Drawable ?
您的Activity应该具有getResources方法 . 做:
Drawable myIcon = getResources().getDrawable( R.drawable.icon );
此代码已弃用 .
Drawable drawable = getResources().getDrawable( R.drawable.icon );
使用此instad .
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
自API 22起, getDrawable (int id) 方法已折旧 .
getDrawable (int id)
相反,您应该使用 getDrawable (int id, Resources.Theme theme) for API 21
getDrawable (int id, Resources.Theme theme)
代码看起来像这样 .
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); }
我想补充一点,如果在使用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前后版本 .
Get Drawable from vector resource irrespective of, whether its vector or not:
AppCompatResources.getDrawable(context, R.drawable.icon);
Note:ContextCompat.getDrawable(context, R.drawable.icon); 将为矢量资源生成 android.content.res.Resources$NotFoundException .
ContextCompat.getDrawable(context, R.drawable.icon);
android.content.res.Resources$NotFoundException
如果您尝试从图像设置为的视图中获取drawable,
ivshowing.setBackgroundResource(R.drawable.one);
那么drawable将仅使用以下代码返回null值...
Drawable drawable = (Drawable) ivshowing.getDrawable();
因此,如果您想从特定视图中检索drawable,最好使用以下代码设置图像 .
ivshowing.setImageResource(R.drawable.one);
只有这样,我们才能准确地改造抽屉 .
6 回答
您的Activity应该具有getResources方法 . 做:
此代码已弃用 .
Drawable drawable = getResources().getDrawable( R.drawable.icon );
使用此instad .
自API 22起,
getDrawable (int id)
方法已折旧 .相反,您应该使用
getDrawable (int id, Resources.Theme theme)
for API 21代码看起来像这样 .
我想补充一点,如果在使用getDrawable(...)时收到“已弃用”消息,则应使用支持库中的以下方法 .
使用此方法时,您不必使用getResources() .
这相当于做类似的事情
这适用于Lollipop前后版本 .
Get Drawable from vector resource irrespective of, whether its vector or not:
Note:
ContextCompat.getDrawable(context, R.drawable.icon);
将为矢量资源生成android.content.res.Resources$NotFoundException
.如果您尝试从图像设置为的视图中获取drawable,
那么drawable将仅使用以下代码返回null值...
因此,如果您想从特定视图中检索drawable,最好使用以下代码设置图像 .
只有这样,我们才能准确地改造抽屉 .