0

我有包含文本视图和按钮的列表视图。当我删除列表视图项目并尝试向下滚动时,我得到了例外:

BuildQueue eile = countryList.get(position);

例外:

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

当我从列表视图中删除项目时,似乎我没有更新某些内容。我想我有 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;

        }
    }
4

1 回答 1

2

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

每个 Adapter 用于getCount()确定应该绘制多少行。ArrayAdaptergetCount()只是在此处询问您传递给超级构造函数的数组的大小super(context, textViewResourceId, countryList);:但是您还使用了第二个本地数组,当您从中删除一个值时,countryList getCount()不知道这会导致getView()抛出 IndexOutOfBoundsException ...

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

于 2013-02-08T18:09:08.207 回答