我是Android新手,所以不確定我在這裏做錯了什麼。我有一個gridview,我正在顯示一堆圖片,我正在使用一個適配器來填充gridview。 gridview滾動非常緩慢/遲緩,所以我嘗試使用asynctask來設置imageviews的圖像資源。出於某種原因,圖像視圖沒有獲取資源,所以它們只是顯示空白。這是我的代碼:Asynctask沒有設置圖像視圖的圖像資源
class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
imageView.setLayoutParams(new GridView.LayoutParams(width/2,(width/2)*515/400));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
//imageView.setImageResource(mThumbIds[position]);
ImageSetter task=new ImageSetter(imageView);
task.execute(position);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.zsmall_artemis,R.drawable.zsmall_ash,R.drawable.zsmall_bane,R.drawable.zsmall_belle,R.drawable.zsmall_caleb,R.drawable.zsmall_falcyn,R.drawable.zsmall_jaden,R.drawable.zsmall_julien,R.drawable.zsmall_kody,
R.drawable.zsmall_mack,R.drawable.zsmall_maxis,R.drawable.zsmall_nero,R.drawable.zsmall_nick,R.drawable.zsmall_nykyrian
};
class ImageSetter extends AsyncTask<Integer,Void,Integer>{
private final WeakReference<ImageView> imageViewReference;
public ImageSetter(ImageView imageview){
imageViewReference=new WeakReference<ImageView>(imageview);
}
@Override
protected Integer doInBackground(Integer... ImagePos){
return mThumbIds[ImagePos[0]];
}
protected void onPostExecute(int ImageId){
if(isCancelled()){
ImageId=mThumbIds[0];
}
if(imageViewReference != null){
ImageView iview = imageViewReference.get();
if(iview != null){
iview.setImageResource(ImageId);
}
}
}
}
}
圖片資源ID都存儲在陣列中,和「位置」是用來表示我指的是哪個數組元素。我該如何解決?
變量ImageView是否需要更正值?你檢查過了嗎? –
此外,我會建議使用像UniversalImageLoader或畢加索圖像庫 –