Android custom navigation drawer menu item with SwitchCompat

This post will walk you through how to create a custom menu item in the navigation drawer menu, with a toggle on and off button on the right using app:actionLayout and a custom layout with SwitchCompat.

1. Create an sample android app from the Android Studio and choose navigation drawer as your default template.

2. Create a layout file action_view_switch.xml



    

3. Replace the content in the res/menu/activity_main_drawer.xml with the following



    
        
        
    

4. Add a class field in MainActivity.java

private SwitchCompat switcher;

5. Add the following code in the onCreate method in MainActivity.java


Menu menu = navigationView.getMenu();
MenuItem menuItem = menu.findItem(R.id.nav_switch);
View actionView = MenuItemCompat.getActionView(menuItem);

switcher = (SwitchCompat) actionView.findViewById(R.id.switcher);
switcher.setChecked(true);
switcher.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
            Snackbar.make(v, (switcher.isChecked()) ? "is checked!!!" : "not checked!!!", Snackbar.LENGTH_SHORT).setAction("Action", null).show();
            }
        });

6. Replace the code in onNavigationItemSelected in MainActivity.java with the following.

int id = item.getItemId();

if (id == R.id.nav_camera) {
    // Handle the camera action
} else if (id == R.id.nav_switch) {
    switcher.setChecked(!switcher.isChecked());
    Snackbar.make(item.getActionView(), (switcher.isChecked()) ? "is checked" : "not checked", Snackbar.LENGTH_SHORT).setAction("Action", null).show();
}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;

7. Run the app, open the navigation drawer menu, you should see the second item on the menu has a toggle on off button on the right.

Complete example in Github
References:
https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer
http://stackoverflow.com/questions/37361091/android-something-like-navigation-drawer-with-custom-filling

Search within Codexpedia

Custom Search

Search the entire web

Custom Search