在ListView中显示来自URL的可绘制图像

5
我希望能在 ListView 中显示新闻(从 RSS 中提取)。我已经成功创建了 ListView 并正确地显示了标题和描述。但是,我无法显示来自 URL 的图像。
以下是我的代码:
maListViewPerso = (ListView) findViewById(R.id.listviewperso);
ArrayList <HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;

int i = 0;
while (i < 55)
{
    map = new HashMap<String, String>();
    map.put("titre", newsArray[i]);
    map.put("description", newsArray[i+1]));
    map.put("img", newsArray[i+4]);
    listItem.add(map);

    i += 5;
}

SimpleAdapter mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, 
R.layout.affichageitem, new String[] {"img", "titre", "description"}, 
new int[] {R.id.img, R.id.titre, R.id.description});

maListViewPerso.setAdapter(mSchedule);

你可以猜到,newsArray[i+4] 包含了我的图片的URL。

我写了一个函数 drawable_from_url,它返回一个 android.graphics.drawable.Drawable 对象,而且它工作得很好。我尝试写下这段代码:

map.put("img", String.valueOf(drawable_from_url(newsArray[i+4], "newsPic")));

但也没有起作用(没有显示图片)。String.valueOf(drawable_from_url(newsArray[i+4], "newsPic"))的一个示例可能是android.graphics.drawble.BitmapDrawable@481f16d0
有任何想法吗?
谢谢。
1个回答

0

尝试使用此方法从URL加载位图

    public  Bitmap setRemoteImage(URL url) {
    try {
        Bitmap bm=null;
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis=new BufferedInputStream(is);
        try {
            bm = BitmapFactory.decodeStream(bis);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            MainActivity mm= new MainActivity();
            Drawable dra=mm.getResources().getDrawable(R.drawable.icon);
            Bitmap bb=((BitmapDrawable)dra).getBitmap();
            bm=bb;
        }
        is.close();
        return bm;
    }catch (IOException e) {
        return null;
    }   
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接