我想从列表视图中删除一个项目

时间:2016-11-02 06:35:57

标签: java android listview android-studio listadapter

我遇到的问题是,每当我删除时,只会删除ListView中的最后一项。我从arraylist中删除了该项目并致电adapter.notifyDataSetChanged()。有什么我想念的吗?此外,当我尝试删除太多项目时,我得到arrayIndexOutOfBounds异常,但我正在通过我收到的索引。为什么我得到这个例外?

public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
            HistoryItem item = historyItems.get(index);
            switch (index) {
                case 0:
                    //ToDo edit
                    //Toast.makeText(History.this,"pos "+position+" index "+index,Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    //ToDo delete

                    historyItems.remove(item);
                    adapter.notifyDataSetChanged();

3 个答案:

答案 0 :(得分:1)

您使用的是编辑或删除按钮位置的索引。 您必须使用Position而不是index来从列表中删除项目 问题发生在HistoryItem item = historyItems.get(index);

解决方案:

HistoryItem item = historyItems.get(position);

答案 1 :(得分:1)

请勿使用index使用position

public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                HistoryItem item = historyItems.get(position);
                switch (index) {
                    case 0:
                        //ToDo edit
                        //Toast.makeText(History.this,"pos "+position+" index "+index,Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        //ToDo delete

                        historyItems.remove(position);
                        adapter.notifyDataSetChanged();

答案 2 :(得分:0)

您正在使用索引变量来删除项目。您需要使用位置变量从历史列表中获取所选项目

在代码中更改此行

HistoryItem item = historyItems.get(position);