I'm following this tutorial to set the popupmenu to some distance away from the right side of the screen: http://ift.tt/1ddW1uv
Similar to this tutorial, my popupmenu touches the rihgt side of the screen:
The author of the tutorial says you can adjust the horizontal offset by using reflection.
I have taken his code and put it into my project but it keeps on returning an error - please note that the piece of his code relating to putting icons within the popupmenu works flawlessly:
Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
The faulty line that the error points to is:
Class listPopupClass = listPopup.getClass();
I don't know enough about reflection to solve this issue, does anyone know why I'm getting a null object reference?
// 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();
Aucun commentaire:
Enregistrer un commentaire