如何在android中自定义弹出菜单

时间:2018-04-12 12:28:43

标签: android popup android-popupwindow

我正在尝试自定义弹出菜单但无法自定义。我曾尝试过很多建议和解决方案,但没有运气来实现这一目标。

请检查并告诉我我错在哪里......

我想像这样创建Popmenu: enter image description here

我尝试过这些代码:

public PopupWindow popupDisplay() {

    final PopupWindow popupWindow = new PopupWindow(context);

    // inflate your layout or dynamically add view
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View view = inflater.inflate(R.layout.hs_popup_item, null);

    popupWindow.setFocusable(true);
    popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
    popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
    popupWindow.setContentView(view);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        popupWindow.setElevation(4);
    }
    popupWindow.setClippingEnabled(true);

    return popupWindow;
}

请指导我如何在弹出菜单中添加子标题(描述)。

1 个答案:

答案 0 :(得分:0)

public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(mContext, v);
popupMenu.inflate(R.menu.album_overflow_menu);

// 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 (Exception e) {
    // Possible exceptions are NoSuchMethodError and NoSuchFieldError
    //
    // In either case, an exception indicates something is wrong with the reflection code, or the 
    // structure of the PopupMenu class or its dependencies has changed.
    //
    // These exceptions should never happen since we're shipping the AppCompat library in our own apk, 
    // but in the case that they do, we simply can't force icons to display, so log the error and
    // show the menu normally.

    Log.w(TAG, "error forcing menu icons to show", e);
    popupMenu.show();
    return;
}

popupMenu.show();
}