PopupMenu没有显示图标以及如何在打开时突出显示PopupMenu项目 [英] PopupMenu not showing icons and how to highlight PopupMenu item when its opened

查看:894
本文介绍了PopupMenu没有显示图标以及如何在打开时突出显示PopupMenu项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用android.support.v7中的PopupMenu。我试图用文字显示图标。但只显示文本。
我尝试使用普通代码: android:icon =@ android:drawable / ic_menu_camera但它不能与PopupMenu一起使用。

I am using PopupMenu from android.support.v7. I am trying to show icons with text. But only text is showing.
I tried to used normal code: android:icon="@android:drawable/ic_menu_camera" but its not working with PopupMenu.

还有一个问题,我们可以在PopupMenu项目打开时突出显示它吗?

One more question, can we highlight PopupMenu item when its opened ?

请检查这里的参考图像

Please check the reference image here

推荐答案

If you are using popup menu just copy the below code and run it, you will get icons in popupmenu

PopupMenu popup = new PopupMenu(getApplicationContext(), view);

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();
}

    popup.getMenuInflater()
                    .inflate(R.menu.publisher, popup.getMenu());

                    //registering popup with OnMenuItemClickListener
                    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        public boolean onMenuItemClick(MenuItem item) {

                            switch (item.getItemId()) {
                            case R.id.menu:
                                //your function
                                return true;
                                                        default:
                                break;
                            }
                            return false;
                        }
                    });
                    popup.show();

这篇关于PopupMenu没有显示图标以及如何在打开时突出显示PopupMenu项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆