【问题标题】:Set a Parsed (JSON) image into background of a layout? [duplicate]将解析的(JSON)图像设置为布局的背景? [复制]
【发布时间】:2013-05-28 10:26:12
【问题描述】:

我有一个演示图片链接:

http://madhabpurps.org/wp-content/uploads/2013/04/28-239x300.jpg

我想在视图持有者类内的布局背景中设置图像:

static class ViewHolder {
    TextView txtName;
    TextView txtCityState;
    RelativeLayout rl;
}

holder.txtName.setText(searchArrayList.get(position).getTitle());
holder.txtCityState.setText(searchArrayList.get(position).getDescription());

我必须从这里的链接设置图像,我试过这行代码但它显示错误。

holder.rl.setBackgroundResource(searchArrayList.get(position).getImage());

【问题讨论】:

  • 你要先下载
  • 能否提供下载图片的代码行?
  • 寻找Android HttpClient

标签: android bitmap hyperlink


【解决方案1】:

我从这里得到答案change background image of Framelayout via URL

private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
        try {
            InputStream is = (InputStream) this.fetch(url);
            Drawable d = Drawable.createFromStream(is, saveFilename);
            return d;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Object fetch(String address) throws MalformedURLException,IOException {
        URL url = new URL(address);
        Object content = url.getContent();
        return content;
    }

然后你就可以这样使用了

Drawable drw = ImageOperations(this,url,filename)
rl.setBackgroundDrawable(drw);

这应该可以解决。但对于一般情况,我推荐另一种方法来解决这些问题。

我建议使用有据可查的图像下载和缓存库。我正在使用毕加索http://square.github.io/picasso/。设置它,使用库很容易。

然后你可以通过写来填充一个imageview

Picasso.with(activity)
 .load(url)
 .fit()
 .into(imageView);

【讨论】:

  • Picasso.with(this) .load(searchArrayList.get(position).getDescription()) .resize(50, 50) .centerCrop() .into(holder.rl);
  • 第一个参数出错
  • 我只是为了示例目的而编写它,第一个参数是上下文,或者在您的情况下是您当前的活动。仅供参考:毕加索示例应用代码在这里github.com/square/picasso/tree/master/picasso-sample
  • 这个链接太棒了..只需将 jar 文件添加到项目中并使用压缩和完美解析任何类型的 Web 链接square.github.io/picasso .....感谢 Yekmer Simsek 提供此链接
【解决方案2】:

使用下面的代码

Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
Drawable d = new BitmapDrawable(getResources(),bitmap);
rl.setBackgroundDrawable(dr);

【讨论】:

  • 您能提供有关 getResources() 的详细信息吗???
  • enter code here 会是什么?应该是“d”
  • getResources() 返回应用程序包的资源实例。如果你不在活动中使用 Context.getResources() 并且你应该知道在 android 3Ice cream sandwish 之后你应该使用单独的线程来调用 http url
  • 位图位图 = BitmapFactory.decodeStream((InputStream)new URL(url).getContent()); Drawable d = new BitmapDrawable(Context.getResources(),bitmap); holder.rl.setBackgroundDrawable(dr);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
  • 2014-05-01
  • 1970-01-01
相关资源
最近更新 更多