我是Android应用程序开发的新手,在练习中我尝试使用以下代码开发应用程序
enter code here
公共类URLImageAdapter扩展了BaseAdapter {
private class Image
{
String url;
Bitmap thumb;
}
private Image[] images;
private Context myContext;
private LoadThumbsTask thumbnailGen;
public URLImageAdapter(Context c, Object previousList)
{
myContext = c;
thumbnailGen = new LoadThumbsTask();
if(previousList != null)
{
images = (Image[]) previousList;
thumbnailGen.execute(images);
return;
}
images = new Image[imageURLs.length];
for(int i = 0, j = imageURLs.length; i < j; i++)
{
images[i] = new Image();
images[i].url = " " +imageURLs[i];
}
thumbnailGen.execute(images);
}
public int getCount()
{
return images.length;
}
public Object getItem(int position)
{
return images[position].url;
}
public long getItemId(int position)
{
return position;
}
public Object getData()
{
if(thumbnailGen != null && thumbnailGen.getStatus() != AsyncTask.Status.FINISHED) {
thumbnailGen.cancel(true);
}
return images;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgView;
Image cached = images[position];
if(convertView == null)
{
imgView = new ImageView(myContext);
imgView.setLayoutParams(new GridView.LayoutParams(100,100));
}
else
{
imgView = (ImageView) convertView;
}
if(cached.thumb == null)
{
imgView.setImageResource(R.drawable.blank);
imgView.setScaleType(ScaleType.CENTER);
}
else
{
imgView.setScaleType(ScaleType.FIT_CENTER);
imgView.setImageBitmap(cached.thumb);
}
return imgView;
}
private void cacheUpdated()
{
this.notifyDataSetChanged();
}
private Bitmap loadThumb(String url)
{
Bitmap thumb = null;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
try
{
URL u = new URL(url);
URLConnection c = u.openConnection();
c.connect();
BufferedInputStream stream = new BufferedInputStream(c.getInputStream());
thumb = BitmapFactory.decodeStream(stream, null, opts);
stream.close();
}
catch (MalformedURLException e)
{
Log.e("Threads03", "malformed url: " + url);
}
catch (IOException e)
{
Log.e("Threads03", "An error has occurred downloading the image: " + url);
}
return thumb;
}
private class LoadThumbsTask extends AsyncTask<Image, Void, Void>
{
@Override
protected Void doInBackground(Image... cache)
{
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
for (Image i : cache)
{
if(isCancelled()) return null;
if(i.thumb != null) continue;
SystemClock.sleep(400);
i.thumb = loadThumb(i.url);
publishProgress();
}
return null;
}
@Override
protected void onProgressUpdate(Void... param)
{
cacheUpdated();
}
}
private String[] imageURLs =sam();
这里sam()是我从webservice
获得imageurl的函数