弹出菜单偏离屏幕右边缘

时间:2015-11-13 17:33:35

标签: java android reflection popupmenu

我按照本教程将弹出菜单设置为距离屏幕右侧一定距离:http://keepsafe.github.io/2014/11/19/building-a-custom-overflow-menu.html

与本教程类似,我的popupmenu触及屏幕的rihgt侧:

popupmenu

本教程的作者说你可以使用反射来调整水平偏移。

我已经把他的代码放到了我的项目中,但它一直在返回错误 - 请注意他的代码片段与弹出菜单中的图标完美无瑕地工作:

  

尝试调用虚方法' java.lang.Class   java.lang.Object.getClass()'在空对象引用上

错误指向的错误行是:

        Class listPopupClass = listPopup.getClass();

我对解决这个问题的反思知之甚少,有谁知道为什么我会得到一个空对象引用?

        // Force icons to show
        Object menuHelper;
        Class[] argTypes;
        try {
            Field fMenuHelper = PopupMenu.class.getDeclaredField("mPopup");
            fMenuHelper.setAccessible(true);
            menuHelper = fMenuHelper.get(popupMenu);
            argTypes = new Class[]{boolean.class};
            menuHelper.getClass().getDeclaredMethod("setForceShowIcon", argTypes).invoke(menuHelper, true);

        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        // Try to force some horizontal offset
        try {
        Field fMenuHelper = PopupMenu.class.getDeclaredField("mPopup");
        fMenuHelper.setAccessible(true);
        menuHelper = fMenuHelper.get(popupMenu);
        Field fListPopup = menuHelper.getClass().getDeclaredField("mPopup");
        fListPopup.setAccessible(true);
        Object listPopup = fListPopup.get(menuHelper);
        argTypes = new Class[] { int.class };
        Class listPopupClass = listPopup.getClass();
        // Get the width of the popup window
        int width = (Integer) listPopupClass.getDeclaredMethod("getWidth").invoke(listPopup);
        // Invoke setHorizontalOffset() with the negative width to move left by that distance
        listPopupClass.getDeclaredMethod("setHorizontalOffset", argTypes).invoke(listPopup, -width);
        // Invoke show() to update the window's position
        listPopupClass.getDeclaredMethod("show").invoke(listPopup);
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
        popupMenu.inflate(R.menu.popup_global);
        popupMenu.show();

0 个答案:

没有答案
相关问题