Search code examples
androidselectpopupmenudismiss

How to dismiss a PopUp Menu when an Item Clicked in Android


I am using popup menu in my code. It works perfectly . but when I select an item from it, menu was not dismissing . I tried this . but it is not working

here is my code

 PopupMenu popup = new PopupMenu(this, edit1);
        //inflating menu from xml resource
        popup.inflate(R.menu.options_menu);
        popup.getMenu().add("one");
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                // if (item.getTitle().equals("one")) {
                Toast.makeText(MainActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();

        popup.dismiss();
        return false;
            }
        });
        //displaying the popup
        popup.show();

Please some one help me.


Solution

  • try this below code it will work for you

     popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    // if (item.getTitle().equals("one")) {
                    Toast.makeText(MainActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
                    popup.dismiss();
    
                    return true;
                }
            });
    

    and as I see your comments if you are using onTouchListener for the EditText. just change it to onClickListener and your problem will be solved.