在长按单击侦听器中删除列表对话框中的项目

时间:2014-08-18 11:05:49

标签: android

我正在使用一个对话框,它显示了我的代码字符串列表的项目

 final CharSequence[] items = {"1", "2", "3"};

            AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
                }

            }).show();

现在我的问题是如何实现 onLongClicklistener 方法删除所选项目我的对话框看起来如图所示 **enter image description here**

2 个答案:

答案 0 :(得分:0)

您需要按如下方式实施onItemLongClick方法:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
        // TODO: Get the position of the item clicked. 
        //       Delete it from your collection eg.ArrayList.
        //       Call notifydatasetChanged so that it will refresh 
        //       the views displaying updated list.
        return true;
    }
});

答案 1 :(得分:0)

1)在列表视图上设置ItemLongClickListener 2)从数组中删除长按项,填充列表适配器 3)刷新适配器

public ListView listView;
public ArrayList<String> items;
public ArrayAdapter adapter;

listView.setOnItemLongClickListener(new OnItemLongClickListener(){ 
    @Override
    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
    String selectedItem = items.get(pos);
    items.remove(selectedItem);
    adapter.notifyDataSetChanged();
    return true;
    }
});