删除LongClick上的Android ListView行

时间:2015-03-21 03:27:23

标签: android listview swipe delete-row

我有这段代码从数据库中获取数据并在ListView中显示

List<Contact> contacts = db2.getAllContacts();
        ArrayList<String> MY_LIST = new ArrayList<>();

        for (Contact cn : contacts) {
            String outputt = "Id: " + cn.getID() + ", Message: " + cn.getMessage() +
                    ", Time: " + cn.getDate();
            MY_LIST.add(outputt);
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this, android.R.layout.simple_list_item_1, MY_LIST);


        ListView listView = (ListView) findViewById(R.id.listView);

        listView.setAdapter(adapter);

我想在滑动时删除ListView上的特定项目/行。 我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

您可以使用EnhancedListView。只需从项目中的链接仓库中复制EnhancedListView类。然后在代码中使用和ListView而不是EnhancedListView。即:

EnhancedListView listView = (EnhancedListView) findViewById(R.id.listView);

// Then set an EnhancedListView.OnDismissCallback:

listView.setDismissCallback(new de.timroes.android.listview.EnhancedListView.OnDismissCallback() {

            @Override
            public EnhancedListView.Undoable onDismiss(EnhancedListView listView, final int position) {

                final String item = (String) adapter.getItem(position);
                adapter.remove(position);
                // If you'd like the user to be able to undo a swipe:
                return new EnhancedListView.Undoable() {
                    @Override
                    public void undo() {
                        adapter.insert(position, item);
                    }
                };
            }
        });

// Enable swipe to dismiss:

listView.enableSwipeToDismiss();

注意:开发人员不再维护repo,而是支持Google的新RecyclerView。但是,只需复制代码中的EnhancedListView类,即可轻松使用它。

答案 1 :(得分:-2)

我花了一整天的时间学习和学习。我是这样做的。

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                           int pos, long id) {
                // TODO Auto-generated method stub

                Log.v("long clicked", "pos: " + pos);

                MY_LIST.remove(pos); //where pos is position of item I click
                adapter.notifyDataSetChanged();

                return true;
            }
        });