简体   繁体   English

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

[英]I want to delete an item from a list view

The problem I'm having is that whenever I delete , only the last item from the ListView is being deleted. 我遇到的问题是,无论何时删除,都只会删除ListView的最后一项。 I remove the item from my arraylist and call adapter.notifyDataSetChanged() . 我从我的arraylist中删除该项目,然后调用adapter.notifyDataSetChanged() Is there anything which I'm missing? 有什么我想念的吗? Also , when I try to delete too many items I get an arrayIndexOutOfBounds exception , but I'm passing the index I recieve. 另外,当我尝试删除太多项目时,出现arrayIndexOutOfBounds异常,但我正在传递我收到的索引。 Why I am getting this exception? 为什么我收到此例外?

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();

You are using index which is position of Edit or Delete buttons.. You have to use Position instead of index to delete item from list The problem is at HistoryItem item = historyItems.get(index); 您正在使用作为“编辑”或“删除”按钮位置的索引。必须使用“位置”而不是索引来从列表中删除项目。问题出在HistoryItem item = historyItems.get(index);

Solution: 解:

HistoryItem item = historyItems.get(position);

Don't use index use position 不要使用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();

You are using index variable to remove items. 您正在使用索引变量删除项目。 You need to use position variable to get the selected items from history list 您需要使用位置变量从历史记录列表中获取所选项目

Change this line in code 在代码中更改此行

HistoryItem item = historyItems.get(position);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM