102

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

Dinesh
  • 965
  • 2
  • 11
  • 23
Redson
  • 2,098
  • 4
  • 25
  • 50
  • you wont be able to do it like that with a standard adatper. you will need to create a custom adapter and have some simple login on getView to hide or show the seperator – Tomer Shemesh May 14 '15 at 17:22
  • @TomerShemesh Do you have an example of how I can do this? – Redson May 14 '15 at 17:23
  • there are libraries on github which will help you achieve the same. MaterialDrawer by mikepenz is a good one and is maintained well. https://github.com/mikepenz/MaterialDrawer. You can also follow google io schedule app on github. The separator is just a view with height 1px and width match_parent – Raghunandan May 14 '15 at 17:23
  • @Raghunandan I know that the separator is a `View` but I need to somehow find a way to only call it for Neptune – Redson May 14 '15 at 17:28
  • @Alias follow google io schedule app or use the library i just posted the link. Both should work – Raghunandan May 14 '15 at 17:29

5 Answers5

360

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.

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
espinchi
  • 9,144
  • 6
  • 58
  • 65
  • 152
    Important to say that if the group doesn't have an id, the separator will not appear! – Gabriel Gómez Jan 03 '16 at 16:28
  • 1
    Looks really good so far, but how to fix the `android:checkableBehavior`? If I select the last item in group2 and click on an item of group1 aftwards, both items are highlighted. @espinchi could you add a solution for this to your answer? – Tomblarom Mar 24 '16 at 15:31
  • 4
    How to apply this menu to NavigationDrawer? – Yar Mar 30 '16 at 08:47
  • @GabrielGómez this is so ugly. Why id is required to show a separator, it's so bad... – user25 Feb 02 '19 at 21:08
  • glad I found this, don't have to use that hack job I had before. – lasec0203 Sep 23 '19 at 06:59
12

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

aminography
  • 21,986
  • 13
  • 70
  • 74
3

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.

Eltee
  • 87
  • 3
1

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);
Mostrapotski
  • 425
  • 3
  • 11
-3

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

<group android:checkableBehavior="none">
    <item android:title="______________________________________________________________"
        android:iconTint="@color/colorWhite"
        android:enabled="false">

    </item>
</group>
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92