图片加载错位

        ListView加载图片错位导致的原因:主要是View的复用,复用View的时候,除了在复用View的同时还会将相应的图片资源进行复用

     

public class MyBaseAdapter extends BaseAdapter {

    private  List dataList;
    private Context context;
    public MyBaseAdapter(Context context,List dataList){
        this.dataList = dataList;
        this.context = context;
    }


    @Override
    public int getCount() {
        return dataList != null ? dataList.size() : 0;
    }
    @Override
    public Object getItem(int position) {
        return dataList.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = null;
        if(convertView == null){
            viewHolder = new ViewHolder();
            convertView = convertView.inflate(context, R.layout.item,null);

            viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
            viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tvContent);

            convertView.setTag(viewHolder);

        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }


        //填充数据
        viewHolder.tvContent.setText("健康标题 : "+dataList.get(position).getTitle()+"\n健康相关描述 : "
        +dataList.get(position).getDescription());

        //设置一个标识
        viewHolder.ivIcon.setTag(dataList.get(position).getImg());
        //加载图片
        loadImage(dataList.get(position).getImg(),viewHolder.ivIcon);
        //设置一个默认图片
        viewHolder.ivIcon.setImageResource(R.mipmap.ic_launcher_round);
        return convertView;
    }

    /**
     * 加载图片
     */
    private void loadImage(final String path, final ImageView ivIcon){


        new ImageLoadAsyncTask(new ImageLoadAsyncTask.NetworkBitmapListener() {
            @Override
            public void callBitmap(Bitmap bitmap) {

                if(bitmap != null){
                    //如果传进来的图片地址与我们我们之前ImageView进行预设的标识相同的话
                    //就证明是同一张图片,就加载 //www.sina.com www.baidu.com
                    if(ivIcon.getTag() != null && path.equals(ivIcon.getTag()) ) {
                        ivIcon.setImageBitmap(bitmap);
                    }
                }else{
                    ivIcon.setImageResource(R.mipmap.ic_launcher);
                }
            }
        }).execute(path);

    }


    class ViewHolder{

        ImageView ivIcon;
        TextView tvContent;

    }


}

你可能感兴趣的:(图片加载错位)