有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java弹出菜单与屏幕右边缘的偏移量

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

与本教程类似,我的弹出菜单也会触及屏幕的右侧:

popupmenu

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

我已经将他的代码放入我的项目中,但它不断返回一个错误-请注意,他的代码中有关在弹出菜单中放置图标的部分工作完美:

Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference

错误指向的故障线路为:

        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) 个答案