Android 仿微信长按列表弹出PopupMenu菜单栏

PopupMenu使用步骤

//这里的anchor是PopupMenu需要依附的view
PopupMenu popupMenu = new PopupMenu(context, anchor);
//填充PopupMenu内容
popupMenu.getMenuInflater().inflate(R.menu.conversation_item_popupmenu, popupMenu.getMenu());
//PopupMenu点击事件
popupMenu.setOnMenuItemClickListener(onMenuItemClickListener);
//PopupMenu消失事件
popupMenu.setOnDismissListener(onDismissListener);
//弹出PopupMenu,默认gravity为Gravity.START
popupMenu.show();

弹出效果如下图所示


Gravity.START

可以使用setGravity()方法来指定弹出窗口与anchor视图的对齐方式,例如修改对齐方式为Gravity.END


Gravity.END

使用起来还是比较简单的,但是好像大部分项目的需求是PopupMenu在用户点击的位置弹出,然而PopupMenu并没有提供在指定坐标弹出的方法,所以只能咱们自己来实现咯!

想让PopupMenu在指定弹出位置,首先咱们得先了解show()方法是如何让PopupMenu弹出来的,所以只能去阅读源码了(Read The Fucking Source Code~)。

    public void show() {
        mPopup.show();
    }

PopupMenu的show()方法很简单,直接把任务转给MenuPopupHelper来处理,处理流程:show() -> tryShow() -> showPopup(0, 0, false, false);

    public void show() {
        if (!tryShow()) {
            throw new IllegalStateException("MenuPopupHelper cannot be used without an anchor");
        }
    }
  //安全判断,检测是否有anchor view
    public boolean tryShow() {
        if (isShowing()) {
            return true;
        }
        if (mAnchorView == null) {
            return false;
        }
        //这就是我们要找的方法,默认坐标是(0,0)
        showPopup(0, 0, false, false);
        return true;
    }

    //xOffset 相对于anchor视图的x坐标
    //yOffset 相对于anchor视图的y坐标
    private void showPopup(int xOffset, int yOffset, boolean useOffsets, boolean showTitle) {
        final MenuPopup popup = getPopup();
        popup.setShowTitle(showTitle);

        if (useOffsets) {
            // If the resolved drop-down gravity is RIGHT, the popup's right
            // edge will be aligned with the anchor view. Adjust by the anchor
            // width such that the top-right corner is at the X offset.
            final int hgrav = GravityCompat.getAbsoluteGravity(mDropDownGravity,
                    ViewCompat.getLayoutDirection(mAnchorView)) & Gravity.HORIZONTAL_GRAVITY_MASK;
            if (hgrav == Gravity.RIGHT) {
                xOffset -= mAnchorView.getWidth();
            }

            popup.setHorizontalOffset(xOffset);
            popup.setVerticalOffset(yOffset);

            // Set the transition epicenter to be roughly finger (or mouse
            // cursor) sized and centered around the offset position. This
            // will give the appearance that the window is emerging from
            // the touch point.
            final float density = mContext.getResources().getDisplayMetrics().density;
            final int halfSize = (int) (TOUCH_EPICENTER_SIZE_DP * density / 2);
            final Rect epicenter = new Rect(xOffset - halfSize, yOffset - halfSize,
                    xOffset + halfSize, yOffset + halfSize);
            popup.setEpicenterBounds(epicenter);
        }

        popup.show();
    }

我们可以看到showPopup方法内有两个参数int xOffset、int yOffset,根据注释可以知道这就是相对于anchor视图的坐标值。所以如果要指定PopupMenu的弹出位置,MenuPopupHelper应该这样处理弹出逻辑:show(int x, int y) -> tryShow(int x, int y) -> showPopup(x, y, true, true)。

但是由于PopupMenu无法调用到MenuPopupHelper的show(int x, int y) 方法,因此我们只能使用反射机制绕过PopupMenu,直接调用MenuPopupHelper的show(int x, int y)方法。

到此为止,已经有了大致的解决思路,接下来看看具体实现。

/**
 * 弹出菜单栏
 *
 * @param context
 * @param anchor                  触发事件的View
 * @param menuRes                 菜单栏内容
 * @param point                   点击事件相对整个屏幕的坐标
 * @param onMenuItemClickListener 菜单栏点击事件
 * @param onDismissListener       菜单栏消失
 */
public static void showPopupMenu(Context context, View anchor, @MenuRes int menuRes, Point point,
                                 PopupMenu.OnMenuItemClickListener onMenuItemClickListener,
                                 PopupMenu.OnDismissListener onDismissListener) {
    //这里的anchor代表PopupMenu需要依附的view
    PopupMenu popupMenu = new PopupMenu(context, anchor);
    //填充PopupMenu内容
    popupMenu.getMenuInflater().inflate(menuRes, popupMenu.getMenu());
    //PopupMenu点击事件
    popupMenu.setOnMenuItemClickListener(onMenuItemClickListener);
    //PopupMenu消失事件
    popupMenu.setOnDismissListener(onDismissListener);
    //通过反射机制修改弹出位置,在点击的位置弹出PopupMenu
    try {
        //获取PopupMenu类的成员变量MenuPopupHelper mPopup
        Field mPopup = popupMenu.getClass().getDeclaredField("mPopup");
        mPopup.setAccessible(true);
        Object o = mPopup.get(popupMenu);
        //MenuPopupHelper -> show(int x, int y)方法
        if (o instanceof MenuPopupHelper) {
            MenuPopupHelper menuPopupHelper = (MenuPopupHelper) o;
            int[] position = new int[2];
            //获取anchor左上角在屏幕上的相对坐标
            anchor.getLocationInWindow(position);
            //计算xOffset、yOffset,相对anchor左下角位置为弹出位置
            int xOffset = (point.x - position[0]);
            int yOffset;
            //菜单高度
            int popupMenuHeight = DensityUtil.dp2px(context, 48 * popupMenu.getMenu().size());
            //如果菜单高度大于底部剩余空间,菜单就会向上弹出;否则向下弹出
            if (ScreenUtil.getScreenHeight(context) - point.y >= popupMenuHeight) {
                yOffset = (point.y - (position[1] + anchor.getHeight()));
            } else {
                yOffset = (point.y - (position[1]));
            }
            menuPopupHelper.show(xOffset, yOffset);
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        //出错时调用普通show方法。未出错时此方法也不会影响正常显示
        popupMenu.show();
    }
}

最终弹出效果如下图所示


指定位置弹出

你可能感兴趣的:(Android 仿微信长按列表弹出PopupMenu菜单栏)