Detecting which selected item (in a ListView) spawned the ContextMenu (Android)

后端 未结 8 828
难免孤独
难免孤独 2020-11-27 12:27

I have a ListView that will allow the user to long-press an item to get a context menu. The problem I\'m having is in determining which ListItem they long-press

8条回答
  •  天涯浪人
    2020-11-27 12:37

    I case you are using SimpleCursorAdapder you may do it like this

        @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        getActivity().getMenuInflater().inflate(R.menu.project_list_item_context, menu);
    
        // Getting long-pressed item position
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        int position = info.position;
    
        // Get all records from adapter 
        Cursor c = ((SimpleCursorAdapter)getListAdapter()).getCursor();                     
    
        // Go to required position
        c.moveToPosition(position);
    
        // Read database fields values associated with our long-pressed item
        Log.d(TAG, "Long-pressed-item with position: " + c.getPosition());
        Log.d(TAG, "Long-pressed-item _id: " + c.getString(0));
        Log.d(TAG, "Long-pressed-item Name: " + c.getString(1));
        Log.d(TAG, "Long-pressed-item Date: " + c.getString(2));
        Log.d(TAG, "Long-pressed-item Path: " + c.getString(3));
    
        // Do whatever you need here with received values
    
    }
    

提交回复
热议问题