Search code examples
androidandroid-layoutandroid-menuandroid-popupwindow

Anchoring a PopupMenu to an ImageView


I have an ImageView that opens a PopupMenu on click. How can I set the PopupMenu to display at a certain position? The PopupMenu will serve as a drop down menu and I would like the top right corner of the PopupMenu to be where the user clicked. See images below for illustration:

What I have currently:

enter image description here

What I want:

enter image description here

The relevant code:

mNavViewDropDown= navViewHeader.findViewById(R.id.navview_header_expand);
mNavViewDropDown.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        PopupMenu popup = new PopupMenu(getContext(), mNavViewDropDown);
        //Inflating the Popup using xml file
        popup.getMenuInflater()
                .inflate(R.menu.menu_navview_header_, popup.getMenu());
        //registering popup with OnMenuItemClickListener
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(
                        getContext(),
                        "You Clicked : " + item.getTitle(),
                        Toast.LENGTH_SHORT
                ).show();
                return true;
            }
        });
        popup.show(); //showing popup menu
    }
});

Solution

  • So instead of using that hacky drop down pop up menu, I realized there is much better tool already made for exactly this:

    https://developer.android.com/guide/topics/ui/controls/spinner#java