Closing an Android Popup Menu

Keywords: java android

Question: 

I am attempting to use a popup menu that uses the view of a dynamically added EditText box.

When I do not create the new popup menu inside the onTouch method, the popup closes as expected but, I could not figure out a way to use the view of the touched EditText this way. Instead the popup would show up in the view of the last added EditText.

View.OnTouchListener subjectListener(final EditText editText) {
        return new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                popupMenu = new PopupMenu(MainActivity.this, editText);
                popupMenu.getMenu().add("works");
                popupMenu.show();
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        popupMenu.getMenu().close();
                        list.get((Integer) editText.getTag()).setText(item.getTitle());
                        return true;
                    }
                });
                return false;
            }
        };
    }

With this code the popup menu shows up exactly where I want it too except it does not close unless I touch another EditText a few times. Which makes me think I am creating multiple popup menu's behind each other or something.

Any ideas?

Answers: