Show popup menu on `ActionBar` item click

谁说胖子不能爱 提交于 2019-11-26 15:51:49

问题


I have an ActionBar with an action item on it. After clicking on the action item, I want to show a popup menu. I implemented this method, but I want to anchor it to the action item or to the ActionBar, not to any view from layout. How to get some kind of view to anchor it from MenuItem?

public boolean onOptionsItemSelected(MenuItem item) {
    PopupMenu popupMenu = new PopupMenu(this, ??????); // What view goes here?
    popupMenu.inflate(R.menu.counters_overflow);
    popupMenu.show();
    // ...
    return true;
}

回答1:


So finally I found solution. When you want to anchor popupmenu to ActionItem in ActionBar you need to find view that renders ActionItem. Simple find view with findViewById() where id is same as id of your menu item in xml.

DISPLAYING POPUP:

public boolean onOptionsItemSelected(MenuItem item) {
    // ...

    View menuItemView = findViewById(R.id.menu_overflow); // SAME ID AS MENU ID
    PopupMenu popupMenu = new PopupMenu(this, menuItemView); 
    popupMenu.inflate(R.menu.counters_overflow);
    // ...
    popupMenu.show();
    // ...
    return true;
}

MENU:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

     ....

     <item
    android:id="@+id/menu_overflow"
    android:icon="@drawable/ic_overflow"
    android:showAsAction="ifRoom"
    android:title="@string/menu_overflow"/>

     ....

</menu>

If menu item is not visible (is in overflow) it does not work. findViewById returns null so you have to check for this situation and anchor to another view.




回答2:


public boolean onOptionsItemSelected(MenuItem item) {
    final View addView = getLayoutInflater().inflate(R.layout.add, null);

            new AlertDialog.Builder(this).setTitle("Add a Word").setView(addView)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            addWord((TextView) addView.findViewById(R.id.title));
                        }
                    }).setNegativeButton("Cancel", null).show();
return (super.onOptionsItemSelected(item));
    }

get full source form here..

http://vimaltuts.com/android-tutorial-for-beginners/android-action-bar-tab-menu-example



来源:https://stackoverflow.com/questions/14729592/show-popup-menu-on-actionbar-item-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!