ListView自定义适配器重复项目

时间:2016-05-04 20:49:34

标签: android listview custom-adapter

这个适配器出了什么问题,当我向下滚动时,我看到底部重复的行,然后再次向上滚动时,我还看到顶部以前不存在的重复行,以及Data项的其余部分没有出现

适配器:

public class ClassesListViewAdapter extends BaseAdapter {
    private Context mContext;
    ArrayList<String> Data = new ArrayList<>();


    public ClassesListViewAdapter(Context context, ArrayList<String> data) {
        Data = data;
        mContext = context;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getCount() {
        return Data.size();
    }
    private class ViewHolder{

        TextView ClassDataTV;

    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = ((Activity)mContext).getLayoutInflater();
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.classes_list_view_item, parent, false);
            holder = new ViewHolder();
            holder.ClassDataTV = (TextView) convertView.findViewById(R.id.ClassDataTV);
            holder.ClassDataTV.setText(Data.get(position));
            convertView.setTag(holder);
        }else{
            holder=(ViewHolder)convertView.getTag();
        }

        return convertView;
    }
}

以及我如何使用它:

    ArrayList<String> v = new ArrayList<>();
    v.add("AAAAAAA");
    v.add("WWWWWwW");
    v.add("VVVVVVV");
    v.add("SSSSSSSSS");
    v.add("QQQQQQQQQ");
    v.add("YYYYYYYY");
    v.add("TTTTTTT");
    v.add("UUUUUUUUUU");
    v.add("zzzzzzzzzzzz");
    v.add("CCCCCCCCCC");
    v.add("HHHHHHHHHHH");
    v.add("IIIIIIIIII");
    v.add("PPPPPPPPP");
    mListView.setAdapter(new ClassesListViewAdapter(getActivity(), v));

1 个答案:

答案 0 :(得分:3)

将以下部分代码放在if-block之外,它将被修复:

doc <- xmlParse('<xml>
<link dst="7456" id="1235">
 <wpt id="1" x="33442"/>
</link>
<link dst="4553" id="4572"/>
<link dst="6222" id="4084"/>
<link dst="3451" id="6884">
 <wpt id="2" x="33442"/>
</link>
<link dst="9374" id="7462">  
 <wpt id="3" x="84733"/>
 <wpt id="4" x="49473"/>
</link></xml>')

ViewHolder 模式背后的逻辑告诉您应该以这种方式执行此操作。当您滚动时,某些引用将不会再次创建并且 @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = ((Activity)mContext).getLayoutInflater(); ViewHolder holder; if (convertView == null) { convertView = inflater.inflate(R.layout.classes_list_view_item, parent, false); holder = new ViewHolder(); holder.ClassDataTV = (TextView) convertView.findViewById(R.id.ClassDataTV); convertView.setTag(holder); }else{ holder=(ViewHolder)convertView.getTag(); } // initialize your view here holder.ClassDataTV.setText(Data.get(position)); return convertView; } 被调用,这会导致您的列表未按预期更新。