This is part two of the Navigation drawer in Android post and it will be a demonstration on how to create a toggle button on the navigation drawer menu and add listeners to track on toggle switch events.

The Exercise

We will continue working on the same project that we created for part one of this post. The first thing we will do is to create a switch item in the drawer menu. We go in the drawermenu.xml file and under the profile item we add a new item:

From the previous project we already know how to add icon for the item. Also you will notice that the last line is turning red, because we don’t have a layout_switch file yet. Click on this line and press Alt+Enter and select – Create layout resource file’layout_switch.xml’.

We will be using linear layout for this layout_switch.xml file and the code will look like this:

Now if you run the application you will see a toggle button on the navigation drawer that you can turn on and off, but it does nothing at this point.

Next we will add a listener for the toggle button and add the case for this item in the switchScreen(int id) method, make it display toast message when the switch is turned on or off.

The code for this case will look like this:

Auto import the missing classes. If you run the app now, you will see that in order for the toggle button to work first we must select the Switch item in the menu. To make the Switch item selected when we click the burger menu icon and the toggle button to work without being obligated to click on the Switch item first, we need to add two more lines of code in the onOptionsItemSelected method:

navigationView.getMenu().performIdentifierAction(, 0);

This method will now look like this:

Now the toggle button works without the extra step of selecting the Switch item first.

You can find the whole project hereĀ

See you in part three. Happy coding!


Spread the love

Leave a Reply

Your email address will not be published.