How to add one section separator for Navigation Drawer in Android?

AndroidAndroid LayoutAndroid FragmentsAndroid ActivityNavigation Drawer

Android Problem Overview


I have a navigation drawer like this image. I want to add a section separator (like the line separating Neptune). It seems simple but I can't find anything on the web that was useful for my case.

Here is my MainActivity:

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
                ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         // The action bar home/up action should open or close the drawer.
         // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action buttons
        switch(item.getItemId()) {
        case R.id.action_websearch:
            // create intent to perform web search for this planet
            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
            intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
            // catch event that there's no activity to handle intent
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Fragment that appears in the "content_frame", shows a planet
     */
    public static class PlanetFragment extends Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
            int i = getArguments().getInt(ARG_PLANET_NUMBER);
            String planet = getResources().getStringArray(R.array.planets_array)[i];

            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                            "drawable", getActivity().getPackageName());
            ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
            getActivity().setTitle(planet);
            return rootView;
        }
    }
}

activity_main.xml:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout>

drawer_list_item.xml:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textColor="#fff"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"/>

I want this to be simple but I can't find anything good on the web. Is there a way that I can isolate Neptune and create a section for it? Does anyone have any suggestions? Thanks.

enter image description here

Android Solutions


Solution 1 - Android

Make sure you define each group with a unique ID, separator won't appear without the ID.

For example, this is my drawer_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group
        android:id="@+id/menu_top"
        android:checkableBehavior="single">
        <item
            android:checked="true"
            android:id="@+id/drawer_item_timeline"
            android:icon="@drawable/ic_timer_grey600_24dp"
            android:title="@string/drawer_timeline"/>
        <item
            android:id="@+id/drawer_item_reports"
            android:icon="@drawable/ic_timetable_grey600_24dp"
            android:title="@string/drawer_reports"/>
    </group>

    <group
        android:id="@+id/menu_bottom"
        android:checkableBehavior="none">

        <item
            android:id="@+id/drawer_item_settings"
            android:icon="@drawable/ic_settings_black_24dp"
            android:title="@string/drawer_settings" >
        </item>
    </group>
</menu>

Sample drawer

Gabriel adds below in the comments that if the group doesn't have an id, the separator will not appear.

Solution 2 - Android

To separate menu items by a divider line, only group items with a unique id like following example:

activity_main_drawer.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">

    <item
        android:id="@+id/nav_apps_and_games"
        android:icon="@drawable/ic_apps_black_24dp"
        android:title="@string/my_apps_and_games" />

    <item
        android:id="@+id/nav_bookmarked_apps"
        android:icon="@drawable/ic_add_bookmark_black_24dp"
        android:title="@string/bookmarked_apps" />

    <item
        android:id="@+id/nav_manage_downloads"
        android:icon="@drawable/ic_downloading_file_black_24dp"
        android:title="@string/manage_downloads" />

    <!-- SET A UNIQUE ID TO THE BELOW GROUP -->
    <group android:id="@+id/group1">

        <item
            android:id="@+id/nav_settings"
            android:icon="@drawable/ic_settings_black_24dp"
            android:title="@string/settings" />

        <item
            android:id="@+id/nav_sign_up"
            android:icon="@drawable/ic_card_membership_black_24dp"
            android:title="@string/sign_up_login" />

    </group>

</menu>

Visual Result:

enter image description here

Solution 3 - Android

My hacky method is similar to Mostrapotski's.

In my Layout for my custom adapter, I'm adding a horizontal separator at the beginning of each item and setting it's visibility to gone.

For the elements that mark the beginning of a new group, I set their visibility to visible so that the separator shows up on top of it.

Solution 4 - Android

You have two choices

  1. Your items can be separated (a list at the top, and classic views at the bottom). Then instead of the listview in your main layout (android:id="@+id/left_drawer") you can have a rather complex LinearLayout including those 3 items (list, separator, and bottom views)
  2. Your items must be exactly as in your example, then you need the separator in the list, you can use some logic in your adapter to draw a view on top of the list item where you need the separator. (meaning your list item won't be a single textview anymore, but a LinearLayout with a gone separator (and visible sometimes, according to your adapter's logic).

To help you with some sample code, can you please post all the items you need in your menu ? We need to know exactly what will be static and what will be scrollable.

Edit: If you want that working with the exemple, get rid of the line

mDrawerList.setAdapter(new ArrayAdapter<String>(this, ...)

You need to supply a home made adapter like this: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView

As i said in 2, in your adapter, you will have logic, and thus you can say in the getView() method

if(myPlanet.isNeptune()) 
    holder.mSepatator.setVisibility(View.VISIBLE);
else 
    holder.mSepatator.setVisibility(View.GONE);

Solution 5 - Android

Add group in Menu file to add divider enter image description here

    </item>
</group>

Solution 6 - Android

Add Group to add divider in navigation drawer

    </item>
</group>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRedsonView Question on Stackoverflow
Solution 1 - AndroidespinchiView Answer on Stackoverflow
Solution 2 - AndroidaminographyView Answer on Stackoverflow
Solution 3 - AndroidLeye Eltee TaiwoView Answer on Stackoverflow
Solution 4 - AndroidMostrapotskiView Answer on Stackoverflow
Solution 5 - AndroidManpreet ChahalView Answer on Stackoverflow
Solution 6 - AndroidManpreet ChahalView Answer on Stackoverflow