How to open Menu Context Android with click button in listview adapter?

后端 未结 2 1744
夕颜
夕颜 2021-02-06 05:54

How to open Menu Context Android with click button in listview adapter ?

I tried with my code, but not show the menu context,

code



        
相关标签:
2条回答
  • 2021-02-06 06:50

    Use like this:

    act_komentar.setOnClickListener(new android.view.View.OnClickListener() {
    
        public void onClick(View v) {
            //To register the button with context menu.
            registerForContextMenu(act_komentar);
            openContextMenu(act_komentar);
    
        }
    });
    
    final int CONTEXT_MENU_VIEW = 1;
    final int CONTEXT_MENU_EDIT = 2;
    final int CONTEXT_MENU_ARCHIVE = 3;
    @Override
    public void onCreateContextMenu (ContextMenu menu, View
    v, ContextMenu.ContextMenuInfo menuInfo){
        //Context menu
        menu.setHeaderTitle("My Context Menu");
        menu.add(Menu.NONE, CONTEXT_MENU_VIEW, Menu.NONE, "Add");
        menu.add(Menu.NONE, CONTEXT_MENU_EDIT, Menu.NONE, "Edit");
        menu.add(Menu.NONE, CONTEXT_MENU_ARCHIVE, Menu.NONE, "Delete");
    }
    
    @Override
    public boolean onContextItemSelected (MenuItem item){
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
            case CONTEXT_MENU_VIEW: {
    
            }
            break;
            case CONTEXT_MENU_EDIT: {
                // Edit Action
    
            }
            break;
            case CONTEXT_MENU_ARCHIVE: {
    
            }
            break;
        }
    
        return super.onContextItemSelected(item);
    }
    

    Output:

    enter image description here

    Hope this will work for you.

    0 讨论(0)
  • 2021-02-06 06:59

    The accepted answer is really not optimal - it may simply be dated.

    button.setOnCreateContextMenuListener((menu, v, menuInfo) -> {
        final MenuItem item = menu.add("item-text");
        item.setOnMenuItemClickListener(i -> {
            doWorkOnItemClick();
            return true; // Signifies you have consumed this event, so propogation can stop.
        });
        final MenuItem anotherItem = menu.add("another-item");
        anotherItem.setOnMenuItemClickListener(i -> doOtherWorkOnItemClick());
    });
    button.setOnClickListener(View::showContextMenu);
    

    Alternatively you can show the context menu in a specific location like so:

    button.setOnClickListener(view -> view.showContextMenu(x, y));
    
    0 讨论(0)
提交回复
热议问题