【问题标题】:Display drawable image from url in a ListView在 ListView 中显示来自 url 的可绘制图像
【发布时间】:2011-09-12 12:58:51
【问题描述】:

我想在 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

有什么想法吗?

谢谢。

【问题讨论】:

    标签: android android-widget


    【解决方案1】:

    试试这个方法从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;
        }   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 2017-10-04
      • 2011-09-14
      • 2014-06-04
      相关资源
      最近更新 更多