0%

GridView自动下载并显示网络图片

关于GridView的使用请查看上一篇文章Android UI设计 图片列表GridView用法,本文讲的是在上一篇文章的基础上实现自动下载显示网络上的图片。 布局XML代码不需要修改,程序代码也基本一致,只要稍稍修改下图片适配器就可以了。

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return myImageURL.length;
        }

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

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

        public View getView(int position, View convertView,
                ViewGroup parent)
            {
              /* ImageView */

              ImageView imageView = new ImageView(this.mContext);
              try
              {
                URL aryURI = new URL(myImageURL[position]);
                /* 打开连接 */
                URLConnection conn = aryURI.openConnection(); 
                conn.connect();
                /* 转变为 InputStream */
                InputStream is = conn.getInputStream();
                /* 将InputStream转变为Bitmap */
                Bitmap bm = BitmapFactory.decodeStream(is);
                /* 关闭InputStream */
                is.close();
                /*添加图片*/
                imageView.setImageBitmap(bm);
              } catch (IOException e)
              {
                e.printStackTrace();
              }

              // 填充ImageView
              imageView.setLayoutParams(new GridView.LayoutParams(150,133));
              imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
              imageView.setPadding(4,2,2,2);
              return imageView;
            }

        // references to our images
       
    }

接着定义图片URL,上文是用mThumbIds,一个数组把预先放在drawable目录的的图片放进去,这里是把多个图片URL放进String[] myImageURL数组。