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

183 Views Asked by At

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.

2

There are 2 best solutions below

0
Gabe Sechan On BEST ANSWER

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.

0
dominicoder On

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.

If you click through to the documentation of the DrawerListener itself, the methods are fairly self-descriptive and well-documented.

If i delete drawerLayout.addDrawerListener(actionBarDrawerToggle), the Navigation Bar still opens when i cklick the HamburgerIcon from my ToolBar.

The listener your are setting is an ActionBarDrawerToggle which, among other things, implements the DrawerListener interface to animate the back arrow as the drawer opens and closes. You can see this for yourself by looking at the source code.