将Parsed(JSON)图像设置为布局背景?

时间:2013-05-28 10:26:12

标签: android bitmap hyperlink

我有一个演示图片链接:

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

2 个答案:

答案 0 :(得分:0)

我从这里得到答案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);

答案 1 :(得分:0)

使用以下代码

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