Android: How to find the position clicked from the context menu

前端 未结 3 1130
星月不相逢
星月不相逢 2020-12-04 21:50

I have a list view filled with data. I set up a context menu for the listview using the following code:

list.setOnCreateContextMenuListener
(
  new View.OnCr         


        
相关标签:
3条回答
  • 2020-12-04 22:38

    You can use the ContextMenu.ContextMenuInfo.

    Something like that:

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int index = info.position;
    }
    

    You can also get the exact View for which the menu is being displayed:

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int index = info.position;
        View view = info.targetView;
    }
    
    0 讨论(0)
  • 2020-12-04 22:38

    OK, to solve problem info null **** use static member and set value from Position of your holder to save the value in longclick method member for example:-

    public class CurrentPosition {
       public static  int Pos{ get; set; }
    }
    
    public bool OnLongClick(View v)
    {
        CurrentPosition.Pos = Position;
        return false;
    }
    

    and use in your context select item:

    public override bool OnContextItemSelected(IMenuItem item)
    {
        switch (item.ItemId)
        {
            case 0:
                return true;
            case 1:
                Toast.MakeText(this,CurrentPosition.Pos.ToString(), ToastLength.Long).Show();
                return true;
            case 2:
                Toast.MakeText(this, "Save", ToastLength.Long).Show();
                return true;
            }
            return true;
        }
    }
    

    C# code

    0 讨论(0)
  • 2020-12-04 22:44
    private static final int EDIT_ID = Menu.FIRST + 3;
    private static final int DELETE_ID = Menu.FIRST + 4;
     @Override
        public void onCreateContextMenu(ContextMenu menu, View v,
                ContextMenu.ContextMenuInfo menuInfo) {
            menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Edit").setAlphabeticShortcut(
                    'e');
            menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete")
                    .setAlphabeticShortcut('d');
        }
    
        @Override
        public boolean onContextItemSelected(MenuItem item) {
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                    .getMenuInfo();
            switch (item.getItemId()) {
            case EDIT_ID:
    
                edit(info.id);
                return (true);
            case DELETE_ID:
    
                delete(info.id);
                return (true);
            }
    
            return (super.onOptionsItemSelected(item));
        }
    
    0 讨论(0)
提交回复
热议问题