Android - 如何在ListView中显示URL中的图像?

时间:2012-07-15 14:15:33

标签: android android-listview imageview android-image

我已经搜索并尝试了很多不同的方法来在ListView中显示来自URL的图像,但我无法让我的代码工作。下面是我下载图像的代码,然后在ListView中显示它们但不知何故它不起作用。

private Drawable LoadImageFromWebOperations(String url)
    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }
        catch (Exception e) 
        {
             return null;
        }
    }

这是我调用上述函数的代码

Drawable image = LoadImageFromWebOperations("http://10.0.0.5/images/logo.jpg");

在此之后我将它放入Map中,然后将Map放入名为“productsList”

的ArrayList中
map.put("avatar", image);
productsList.add(map);

最后,我使用SimpleAdapter

在ListView中显示HashMap
ListAdapter adapter = new SimpleAdapter(
   Home.this, productsList, 
   R.layout.list_item, new String[] { TAG_PID,
   TAG_NAME, "url", "avatar"},
   new int[] { R.id.pid, R.id.name, R.id.url, R.id.avatar });

我的应用程序显示除图像之外的所有内容。我在谷歌上搜索过这个问题,但无法得到任何帮助。任何帮助表示赞赏?

2 个答案:

答案 0 :(得分:1)

try

if (image != null) {

                Bitmap bitimage = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 1;
                try {

                                           //bitimage = BitmapFactory.decodeStream((InputStream) new URL(data.getThumbnail().toString().trim().toString()).getContent(), null, options);
                                            bitimage = BitmapFactory.decodeStream((InputStream) new URL(ed).getContent(), null, options);
                    image.setImageBitmap(bitimage);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

答案 1 :(得分:0)

这肯定会对您有所帮助,

CustomAdapter adapter = new CustomAdapter(Home.this, productsList, R.layout.list_item,
new String[] { TAG_PID,TAG_NAME, "url", "avatar"},
 new int[] { R.id.pid, R.id.name, R.id.url, R.id.avatar });

创建一个CustomAdapter类,它扩展SimpleAdapter,覆盖getView()方法,

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View v =  super.getView(position, convertView, parent);
    HashMap<String, Object> hm = (HashMap<String, Object>) super.getItem(position);
    ImageView image = (ImageView) v.findViewById(R.id.yourImageID);
    TextView txt1 = (TextView) v.findViewById(R.id.yourtxtID1);
    TextView txt2 = (TextView) v.findViewById(R.id.yourtxtID2);
    TextView txt3 = (TextView) v.findViewById(R.id.yourtxtID3);


    image.setImageDrawable((Drawable) hm.get("avatar"));
    txt1.setText(hm.get("TAG_PID").toString());
    txt2.setText(hm.get("TAG_NAME").toString());
    txt3.setText(hm.get("url").toString());

    return v;

}

如果问题仍然存在,请告诉我。