android-长时间单击从ListView删除项目 [英] android - removing item from ListView on long click

查看:63
本文介绍了android-长时间单击从ListView删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在长时间单击试图从列表视图中删除项目时,我遇到了一些麻烦.下面是代码:

I'm having some troubles while trying to remove an item from the list view on long click. Below is the code:

public class MListViewActivity extends ListActivity {

private ListView lv;
private String[] some_data = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    some_data = getResources().getStringArray(R.array.mdata);

    // Bind resources Array to ListAdapter
    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this,
            R.layout.list_item, R.id.label, some_data);
    this.setListAdapter(myAdapter);

    lv = getListView();
    lv.setDividerHeight(3);

    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                int arg2, long arg3) {

            // Can't manage to remove an item here

            return false;
        }
    });
}

感谢您的帮助

推荐答案

您不应使用Arrays,而应使用ArrayList删除项目并将其添加到Listview.

You shouldn't use Arrays, you should use ArrayList to remove and add items to a Listview.

声明数组大小后,您可以修改特定索引中的数据,但不能删除项目或将其添加到其中.

Once the Array size is declared you can modify the data in particular index but cannot remove the items or add to it.

因此,获取一个ArrayList,然后长按ListView Item,只需调用Arraylist的remove方法并通知数据集已更改.

So Take an ArrayList and just when you long click on the ListView Item, just call remove method of Arraylist and notify the data set changed.

示例:

ArrayList<String> al = new ArrayList<String>();

在longclick内部编写以下代码以删除项目.

inside your longclick write the below code to remove item.

al.remove(arg2);//where arg2 is position of item you click
myAdapter.notifyDataSetChanged();

这篇关于android-长时间单击从ListView删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆