How to add dividers between specific menu items?

后端 未结 7 1933
旧巷少年郎
旧巷少年郎 2020-12-03 01:35

Background

I have a menu item in the action bar (toolbar actually) that when clicked, shows a list of items to choose from, similar to radio-buttons:



        
7条回答
  •  孤街浪徒
    2020-12-03 01:51

    As of SDK version 28, you can use menu.setGroupDividerEnabled(boolean). If you're using ContextMenu this is only supported on SDK 28+, but MenuCompat offers backwards compatibility when used in onCreateOptionsMenu().

    This will add a divider between the actions for each different groupId, shown as 0 and 1 below:

    menu.add(0, getAdapterPosition(), action1, R.string.action1);
    menu.add(1, getAdapterPosition(), action2, R.string.action2);
    menu.setGroupDividerEnabled(true); 
    
    // Or for MenuCompat < SDK 28:
    MenuCompat.setGroupDividerEnabled(menu, true);
    

    Documentation here: https://developer.android.com/reference/android/view/Menu#setGroupDividerEnabled(boolean)


    EDIT: Sample code as requested by asker:

    Here's the code I am currently using in my app, located in a RecyclerView Adapter. It should work with your menu implementation as well. Since you're defining the menu by XML, the below will also work for you as long as you reference the menu resource. Here's what the result looks like:

    Override onCreateContextMenu or your menu's relevant onCreate.. method like so within the:

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle(getStr(R.string.actions_title));
    
        // Groups 0 and 1, first parameter for menu.add()
        menu.add(0, getAdapterPosition(), 0, R.string.homescreen);
        menu.add(0, getAdapterPosition(), 1, R.string.lockscreen);
        menu.add(0, getAdapterPosition(), 2, R.string.wpLocation_both);
        menu.add(1, getAdapterPosition(), 3, R.string.action_download);
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            menu.setGroupDividerEnabled(true);  // This adds the divider between groups 0 and 1, but only supported on Android 9.0 and up.
        }
    }
    

提交回复
热议问题