如何在单击按钮时从

如何在单击按钮时从

本文介绍了如何在单击按钮时从 ListView 动态删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,需要从按钮事件的 ListView 中删除项目.

I am working on an app that requires removing items from a ListView on a button event.

我尝试从 ArrayList 中删除它并创建全新的适配器并再次加载列表.由于我的列表很大,这样做会影响我的应用程序的性能.所以我想知道是否有任何其他方式可以动态地从我的列表中删除一个项目.

I tried to remove it from ArrayList and create the whole new adapter and load the list again. As my list is huge, doing this will affect the performance of my app. So I was wondering if there is any other way by which I could remove an item from my list dynamically.

我试过你说的.

当我删除一个项目时,它运行良好,但随着我增加所选项目的数量,它开始给我 IndexOutOfBoundException.

When I removed one item it worked perfectly, but as I increase the number of selected items it starts giving me IndexOutOfBoundException.

这是我的代码:

public void onClick(View view)
{
    SparseBooleanArray checkedPositions = new SparseBooleanArray();
    checkedPositions.clear();
    checkedPositions = lv.getCheckedItemPositions();
    int size = checkedPositions.size();
    if(size != 0)
    {

        for(int i = 0; i <= size; i++)
        {
            if(checkedPositions.valueAt(i))
            {
                list.remove(notes.getItem(checkedPositions.keyAt(i)));
                notes.notifyDataSetChanged();
            }
        }
    }
        else{}
}

这里,notes 是对 SimpleAdapter 对象的引用.

Here, notes is a reference to an object of SimpleAdapter.

推荐答案

好吧,您只需使用 ArrayAdapterremove() 方法从列表中删除所需的项目.

Well you just remove the desired item from the list using the remove() method of your ArrayAdapter.

一种可能的方法是:

Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);

另一种方法是修改 ArrayList 并在 ArrayAdapter 上调用 notifyDataSetChanged().

Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.

arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();

这篇关于如何在单击按钮时从 ListView 动态删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 03:04