【问题标题】:Getting an image from a string in an Adapter从适配器中的字符串获取图像
【发布时间】:2017-11-25 12:16:21
【问题描述】:

通过使用getImage(),我得到了 assets/images 文件夹中文件的名称,但我不知道如何创建位图。我不能使用getResorces(),因为该类不是Activity

如何创建将文件名存储在字符串中的位图?

 public class ListAdapter extends BaseAdapter {
     ...
     ...
     ....

    private Bitmap getImage(Node node){
       String path = node.getFirstChild().getFirstChild().getNextSibling().getNextSibling().getNextSibling().getTextContent();
    }
}

【问题讨论】:

  • 如何从资产加载文件的代码已发布一百次。此外,您可以为您的班级提供活动上下文,这样就没有问题了。
  • I cannot use getResorces(), because the class is not an Activity. 不,您无法通过getResources() 检索文件,因为它位于assets 文件夹中。

标签: android bitmap


【解决方案1】:

没有Context,你不能调用getResources() 方法。因此,在ListAdapter 中获取上下文的最佳选择是创建一个将上下文作为参数的构造函数。

public class ListAdapter extends BaseAdapter {
    Context mContext;
    ListAdapter(Context context){
    mContext = context;
    }
    //Your code...
}

如果资产文件夹中有图片

Bitmap getImage(Node node){
    String fileName = node.getFirstChild().getFirstChild().getNextSibling().getNextSibling().getNextSibling().getTextContent();
    try {
        InputStream stream = mContext.getAssets().open(fileName);
        Bitmap bitmap = BitmapFactory.decodeStream(stream);
        return bitmap;
    }catch(IOException e) {
      //Handle this case
    }
return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多