【问题标题】:Set BitmapDrawable resource in constructor在构造函数中设置 BitmapDrawable 资源
【发布时间】:2011-03-11 10:58:53
【问题描述】:

如何在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?
    }

    ...
}

【问题讨论】:

    标签: android resources drawable


    【解决方案1】:

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

    您只需要引用您的上下文。

    【讨论】:

    • 如果我在上下文不可用的地方,那么我如何从资源 id 设置位图(我已经派生了 BitmapDrawable)
    • 你必须传入上下文,或者在你有上下文的地方获取可绘制对象并将可绘制对象传入。请参见此处:stackoverflow.com/questions/9192886/…
    【解决方案2】:

    getResources().getDrawble(int id) 在 API 22 中已被弃用。强烈建议改用 contextCompat.getDrawble(Context ctx, int id)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2012-07-10
      相关资源
      最近更新 更多