GridView Adapter AsyncTask在显示图像时出现奇怪的行为

时间:2012-09-08 11:56:23

标签: android http listview gridview android-asynctask

我需要你的帮助!

在我的应用程序中,在GridView中显示图像时出现奇怪的行为。单元格显示图像而不是默认的R.id.noimage和之前查看过的图像。在我的适配器中添加加载位图AsyncTask后,会出现此错误。

我做错了什么?

代码:

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = new ViewHolder();
    View vi = null;
    ImageView image;
    if(convertView==null) {
        vi = inflater.inflate(R.layout.gall_item, null);
        Log.i("info","convertView==null");
    } else {
        vi = inflater.inflate(R.layout.gall_item, null);
        Log.i("info","else");
    }
    holder.position = position;
    image = (ImageView)vi.findViewById(R.id.img);
    TextView url_img = (TextView)vi.findViewById(R.id.url_img);
    TextView cer = (TextView)vi.findViewById(R.id.cer);
    TextView idi = (TextView)vi.findViewById(R.id.ids);
    url_img.setText(img2[position]);
    cer.setText(cer_ar[position]);
    idi.setText(id_ar[position]);
    new LoadImageT(holder).execute(image, img1[position],activity.getApplicationContext(),position);
    return vi;
}

class LoadImageT extends AsyncTask<Object, Void, Bitmap> {
    Context context;
    private ImageView imv;
    private String url;
    private Bitmap bitmap = null;
    private int posS;
    private ViewHolder mHolder;

    public LoadImageT(ViewHolder holder) {
        mHolder = holder;
    }

    @Override
    protected Bitmap doInBackground(Object... params) {
        imv = (ImageView) params[0];
        url = (String) params[1];
        context = (Context)params[2];
        posS = (Integer) params[3];
        bitmap = imageLoader.getBitmaptrue(url,imv,context);
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (mHolder.position == posS) {
            imv.setVisibility(View.VISIBLE);
            imv.setImageBitmap(result);
        } else {
            int stub_id = R.drawable.noimage;
            imv.setImageResource(stub_id);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你是以错误的方式做的,首先,如果你的视图为null,并且你建议你对视图进行膨胀并设置标记,然后在它不为空时使用此标记,但它只会影响列表视图的效率。其次,从适配器中删除您的异步任务代码,将其放入活动并使用该对象。看到这个link吉尔斯很好地解释了如何以有效的方式进行多线程。