Search code examples
androidnavigation-drawerlistenerdrawerlayout

Android Studio. For what is drawerlayout.addDrawerListener() good for?


i wonder why its needed to use for the NavigationBar the following code snippet?

actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);

    drawerLayout.addDrawerListener(actionBarDrawerToggle);

If i delete drawerLayout.addDrawerListener(actionBarDrawerToggle), the Navigation Bar still opens when i cklick the HamburgerIcon from my ToolBar. Clicks inside the NavBar seems to be handled by NavigationView.setNavigationItemSelectListener().

The official documentation says to addDrawerlistener():

Adds the specified listener to the list of listeners that will be notified of drawer events.

I dont understand this. What is meant by drawer events. Would be very thankfull, if someone could explain to me.


Solution

  • The addListener function allows you to specify a function that will be called when the drawer opens or closes. You're using a ActionBarDrawerToggle with it, which has a listener function which changes the associated text string. You notice that it will change from "open" to "close" when you open the drawer, and back when you close.

    This is kind of a trivial use of it, but there are situation where you may need to do other things. For example you could use it to make a network call to refresh the data in the drawer when it's opened. Or you may want other areas of your UI to go invisible when the drawer is open. It's a chance to hook in any functionality your app may need that isn't standard.