Custom Menu on button click as drop down

拈花ヽ惹草 提交于 2019-11-29 12:20:25
Haresh Chhelana

Try this way,hope this will help you to solve your problem.

Please follow link instruction to shown popup menu item with image and you can use showAtLocation() to shown popup as desired location.

Check : PopupMenu with icons

A simple way I have is put the overflow menu by you and add all those menu as sub menu in that, by that way you achieve this view. Also this overflow menu display as always in your ActionBar

<item
    android:icon="@drawable/ic_action_overflow"
    android:showAsAction="always">
    <menu>

        <item
            android:id="@+id/menu_login"
            android:icon="@drawable/login"
            android:title="login"/>
    </menu>
</item>
Anton

You can easily use ListPopupWindow and any convenient for you adapter:

// create any adapter with any data, just as for ordinary ListView
    SimpleAdapter simpleAdapter= new SimpleAdapter(this, dataSet, android.R.layout.simple_list_item_2,
                            new String[] {"Name", "Tel. no."},
                            new int[] {android.R.id.text1, android.R.id.text2});

ListPopupWindow listPopup = new ListPopupWindow(this); // feed context to ListPopupWindow
listPopup.setAdapter(simpleAdapter); // set adapter to created ListPopupMenu

listPopup.setAnchorView(findViewById(id)); 
// id - any id of any view on the screen. Under this view popup appears. It may be MenuItem as well

listPopup.setWidth(getWidestView(simpleAdapter)); 
// as popup width equals the anchor width, use getWidestView method for proper list displaying. 
// ListPopupWindow.WRAP_CONTENT won't work here

listPopup.show();

getWidestView snippet you can find here: https://stackoverflow.com/a/13959716/4890659

If you're looking for a more Material popup menu and are not afraid of Kotlin you could try: https://github.com/zawadz88/MaterialPopupMenu - there's no need to declare menus in XML and you could handle clicks more easily.

The only way that I could get the icons to show was by calling setForceIcons before inflating the menu.

/**
 * Make a call to setForceIcons to cause icons to show.
 *
 * @param popup
 */
public static void showForceIcons (final PopupMenu popup)
{
    try {
        Field[] fields = popup.getClass().getDeclaredFields();
        for (Field field : fields) {
            if ("mPopup".equals(field.getName())) {
                field.setAccessible(true);
                Object menuPopupHelper = field.get(popup);
                Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName());
                Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class);
                setForceIcons.invoke(menuPopupHelper, true);
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!