从列表视图中删除项目

时间:2013-02-08 18:00:43

标签: java android listview android-arrayadapter

我有listview,其中包含textview和按钮。当我删除listview项目并尝试向下滚动时,我得到例外:

BuildQueue eile = countryList.get(position);

例外:

02-08 19:11:04.279: E/AndroidRuntime(10509): java.lang.IndexOutOfBoundsException: Invalid index 15, size is 15

当我从listview中删除项目时,似乎我没有更新内容。我觉得ViewHolder有问题,但我不知道是什么......

我的ArrayAdapter代码:

public class MyCustomAdapter extends ArrayAdapter<BuildQueue> {

        private ArrayList<BuildQueue> countryList;

        public MyCustomAdapter(Context context, int textViewResourceId,ArrayList<BuildQueue> countryList) {
            super(context, textViewResourceId, countryList);
            this.countryList = new ArrayList<BuildQueue>();
            this.countryList.addAll(countryList);
        }

        private class ViewHolder {
            TextView code;
            TextView field;
            Button del;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = vi.inflate(R.layout.queue_buildings, null);

                holder = new ViewHolder();
                holder.code = (TextView) convertView.findViewById(R.id.code);
                holder.field = (TextView) convertView.findViewById(R.id.field_text);
                holder.del = (Button) convertView.findViewById(R.id.del_button);
                convertView.setTag(holder);

                holder.del.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        Button del_button = (Button) v;
                        BuildQueue building = (BuildQueue) del_button.getTag();
                        countryList.remove(building);
                        dataAdapter.notifyDataSetChanged();
                    }
                });
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            BuildQueue eile = countryList.get(position);
            holder.code.setText(" ( Level: " + eile.getOld_level() + " to "+eile.getNew_level()+")");

            holder.field.setText(eile.getNameSort());
            holder.field.setTag(eile);

            holder.del.setText("Delete");
            holder.del.setTag(eile);

            return convertView;

        }
    }

1 个答案:

答案 0 :(得分:2)

您在适配器中使用了两个阵列,但只更改了其中一个阵列。

每个适配器使用getCount()来确定应绘制多少行。 ArrayAdapter的getCount()只是询问你传递给超级构造函数的数组的大小:super(context, textViewResourceId, countryList);。但是你也在使用第二个本地数组,当你从countryList getCount()中删除一个值时,不知道发生这种情况会导致getView()抛出一个IndexOutOfBoundsException ......

扩展BaseAdapter,或使用ArrrayAdapter的方法,如getItem()add()remove(),并删除您的本地数据集。