简体   繁体   中英

Delete item in the list view using Context Menu

I want to use the context menu to delete an entry from the list view. This is my code:

@Override
public boolean onContextItemSelected(MenuItem item) {
    // Log.d("", "logger enter onContextItemSelected");
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
            .getMenuInfo();
    switch (item.getItemId()) {
    case 1:
        int i = (int) info.id;

        String list_record = separated.get(info.position);

        Utils.removeLabels(this, list_record);
        Log.d("", "labels>>> position: " + info.position);

        separated.remove(info.position);
        Log.d("", "labels>>> separated=" + separated);
        clAdapter.notifyDataSetChanged();

        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

Here, info.position extracts the correct list_record but when I use the same thing in info.position, the item just below the selected item gets deleted. How do I go about this?

This should work:

//This is just an hack

int id = info.position == 0 ? 0 : info.position -1;
clAdapter.remove(clAdapter.getItem(id));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM