How to add line divider for menu item Android

phongvan picture phongvan · Dec 1, 2015 · Viewed 27.8k times · Source

My menu item become bigger so that I want group them and make a line divider to separate each group. What should I do now ?

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
<!--group1-->
            <item
                android:id="@+id/action_addtag"
                android:title="@string/add_hashtag_string"
                app:showAsAction="never" />
            <item
                android:id="@+id/action_block_list"
                android:title="Block"
                app:showAsAction="never" />
            <item
                android:id="@+id/action_report_list"
                android:title="Report"
                app:showAsAction="never" />
<!--group2-->
            <item
                android:id="@+id/terms"
                android:title="Terms"
                app:showAsAction="never" />
            <item
                android:id="@+id/feedback"
                android:title="FeedBack"
                app:showAsAction="never" />
<!--group3-->
            <item
                android:id="@+id/action_setting"
                android:title="Setting"
                app:showAsAction="never" />
    </menu>

Answer

HannaY picture HannaY · Jul 24, 2018

Make sure to call MenuCompat.setGroupDividerEnabled(menu, true); when you inflate your menu, otherwise groups will not be separated by divider!

Example:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_activity_main, menu);

    MenuCompat.setGroupDividerEnabled(menu, true);

    return true;
}

And make sure to have different groups in your menu xml, e.g.:

    <menu>
        <group android:id="@+id/sorting" >
            <item
                android:id="@+id/action_sorting_new_old"
                android:title="@string/action_sorting_new_old"/>

            <item
                android:id="@+id/action_sorting_a_z"
                android:title="@string/action_sorting_a_z"/>
        </group>

        <group android:id="@+id/settings">
            <item
                android:id="@+id/action_settings"
                android:title="@string/action_settings"/>
        </group>
    </menu>