如何在ListView中从Internet下载图像?

时间:2014-12-04 14:36:43

标签: android android-listview

如何从ListView中的URL创建启动映像,我尝试使用this附加组件实现,但错误采用NullPointerExeption。我也使用这个listView以横向格式显示它。这是我的代码出现在listView:

    @Override
public void onCreate(Bundle savedInstanceState) {
        ...
    image_list_icon = (ImageView) findViewById(R.id.image_fromlist);
   HorizontalListView listview = (HorizontalListView) findViewById(R.id.listview);
    listview.setAdapter(mAdapter);


}
private static String[] dataObjects = new String[]{ "Text #1",
        "Text #2",
        "Text #3","Text #3","Text #3" };

private BaseAdapter mAdapter = new BaseAdapter() {
    ArrayList<Object> objects;
    @Override
    public int getCount() {
        return Integer.MAX_VALUE;//
    }

    @Override
    public Object getItem(int position) {
         return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_leyout, null);
        TextView title = (TextView) retval.findViewById(R.id.title);
        title.setText(dataObjects[position%dataObjects.length]);

        try {
                if (title.getText() == "Text #1") {
                    ImageLoader imageLoader=new ImageLoader(context);
                    imageLoader.DisplayImage("http://www.learn2crack.com/wp-content/uploads/2014/06/Untitled.png", image_list_icon);
                }
        } catch (Exception e) {
            Log.d("Ex",e.getMessage());
            return null;
        }
        return retval;
    }

};

1 个答案:

答案 0 :(得分:1)

我建议您使用名为Picasso的库。它解决了围绕图像和内存管理的许多问题。它也很容易使用。

对于列表视图,在适配器getView()中,您只需执行此操作:

ImageView myImageView = (ImageView)view.findViewById(R.id.myImage)

Picasso.with(context)
       .load(imageUrl)
       .into(myImageView);

请参阅http://square.github.io/picasso/