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

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


当前回答

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

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

其他回答

此代码已弃用:

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

用这个代替:

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

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

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

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

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

我只是想补充一点,如果你在使用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]);
}

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

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

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