我必須創建一個畫廊與下載的圖像,我想顯示加載圖像,而我下載它們。 我用這個適配器:在視圖改變爲下載的圖像如何自動更改圖片與從網上下載的圖片?
public class GridViewImageAdapter extends BaseAdapter {
Context context;
public ImageView imageView;
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth,Context context1) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
this.context=context1;
}
public int getCount() {
return this._filePaths.size();
}
public Object getItem(int position) {
return this._filePaths.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imageView = new ImageView(_activity);
} else {
imageView = (ImageView) convertView;
}
imageView.setBackgroundResource(R.drawable.gallery_image);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,imageWidth));
Log.e("Position",position+"");
new RetreiveBitMap().execute(_filePaths.get(position));
return imageView;
}
class RetreiveBitMap extends AsyncTask<String,Integer,Bitmap> {
private Exception exception;
protected Bitmap doInBackground(String... urls) {
Bitmap bm = null;
URL myFileUrl =null;
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
try {
myFileUrl= new URL(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
String encodedfilename = Base64.encodeToString(urls[0].getBytes(),0);
//Controllo presenza della cache
try {
InputStream check = context.openFileInput(encodedfilename);
} catch (FileNotFoundException e) {
// Se non presente, scarico il file
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
//Salvataggio cache
FileOutputStream fos = context.openFileOutput(encodedfilename, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) > 0) {
fos.write(buffer,0, len1);
}
fos.close();
}
bm = BitmapFactory.decodeStream(context.openFileInput(encodedfilename),null,options);
} catch (IOException e) {
Log.e("errore download",e.getMessage());
}
return bm;
}
protected void onPreExecute() {
imageView.setImageResource(R.drawable.spinner);
}
protected void onPostExecute(Bitmap imageBit) {
imageView.setImageBitmap(imageBit);
}
}
}
有了這個代碼,只有最後一張圖像。 出現的圖像應該是網格中的第一個,而不是最後一個!
我剛剛做了使用畢加索(由Square),它需要幾分鐘的時間來實現。至少有兩個可用於Android的免費庫可以做到這一點。 – 323go