show drop down menu within/from action bar

show drop down menu within/from action bar

show drop down menu within/from action bar

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>

or you can dynamically genereate the popup menu as this:

View menuItemView = findViewById(R.id.menu_dropdown); // SAME ID AS MENU ID

PopupMenu popup = new PopupMenu(MainActivity.this, menuItemView);

android.view.Menu menu = popup.getMenu();
menu.add("test").setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(android.view.MenuItem item) {
            return true;
        }
    });
}

popup.show();

There are more usage availble here.


Post by: Jalen Wang (转载请注明出处)

posted on 2013-10-31 23:03  Jalen Wang  阅读(295)  评论(0编辑  收藏  举报

导航