在构造函数中设置BitmapDrawable资源

时间:2011-03-11 10:58:54

标签: android resources drawable

如何在BitmapDrawable构造函数中设置资源?在下面的示例中,我想将资源设置为R.drawable.default_fb_pic,这是一个ID,而不是资源。我怎样才能获得资源? 使用ImageView,我们可以使用其ID设置资源:

imageview.setImageResource(R.drawable.whatever);  

我不清楚为什么有时可以直接使用其ID设置资源,有时不能。

有人可以帮忙吗?

static class DownloadedDrawable extends BitmapDrawable {            

    public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {
        super(R.drawable.default_fb_pic); //"The constructor BitmapDrawable(int)
        //is undefined",
        //which I understand because it takes a resource.
        //But how do I get the resource and why is there no constructor
        //directly with the id?
    }

    ...
}

2 个答案:

答案 0 :(得分:5)

Context.getResources()

http://developer.android.com/reference/android/content/Context.html#getResources()

你可以用

链接它
getDrawable()

http://developer.android.com/reference/android/content/res/Resources.html#getDrawable(int)

mContext.getResources().getDrawable(R.drawable.default_fb_pic);

您只需要参考上下文。

答案 1 :(得分:3)

getResources()。getDrawble(int id)已在API 22中折旧。强烈建议使用contextCompat.getDrawble(Context ctx,int id)。