删除 LongClick 上的 android ListView 行

Deleting an android ListView row on LongClick

我有这段代码可以从数据库中获取数据并显示在 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 上的特定 item/row。 我怎样才能做到这一点?

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

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

注意:开发人员不再维护回购协议,取而代之的是 Google 的新 RecyclerView。但是您只需在代码中复制 EnhancedListView class 即可轻松使用它。

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

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