How to pass variables on long press on ListView?

后端 未结 2 521
终归单人心
终归单人心 2021-01-24 06:54

I would have listview and a lot of items inside. I want that user can long press on item and set it as Favorite. To do that, I need to get DB id to this menu on long press.

相关标签:
2条回答
  • 2021-01-24 07:38

    The ContextMenu.ContextMenuInfo you get passed contains information about which item in the list was clicked. You can probably use this to get the information you need.

    Update:

    Somewhat like dziobas mentions in his answer you can do something like this to get to know which position the selected item has in your adapter:

    AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
    long arrayAdapterPosition = menuInfo.position;
    

    Now you know the position, and can fetch it from your ArrayAdapter. If you have this ArrayAdapter instance stored in a member variable (in this example I have named it myArrayAdapter), you can then proceed to get the item with ArrayAdapter.getItem(int position):

    ToDoItem todoItem = (ToDoItem)myArrayAdapter.getItem(arrayAdapterPosition);
    String task = todoItem.getTask();
    int id = todoItem.getId();
    

    You could now proceed to set the menu header title as follows:

    menu.setHeaderTitle("Favorite: " + task + Integer.toString(id));
    
    0 讨论(0)
  • 2021-01-24 07:46

    If your adapter supports getting Id, so it should look like this:

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
        long id = menuInfo.id;
        ...
    
    0 讨论(0)
提交回复
热议问题