I want to call some methods when Navigation Drawer is opened & closed. How can I listen to it (like button\'s onclick listener) ?
I know we can check (mDra
KOTLIN
Initialize the DrawerLayout View
`val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)`
If you want to take actions automatically when the drawer is opened or closed, you can do the following.
In your main activity, create an inner class that is a subclass of DrawerLayout.DrawerListener. The DrawerLayout class implements the DrawerListener interface. As mentioned in this post, the onDrawerSlide function can be used to take an action when the drawer starts to open.
inner class CustomDrawer : DrawerLayout.DrawerListener{
override fun onDrawerStateChanged(newState: Int) {
}
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
imm.hideSoftInputFromWindow(drawerView?.getWindowToken(), 0)
}
override fun onDrawerClosed(drawerView: View) {
imm.hideSoftInputFromWindow(drawerView?.getWindowToken(), 0)
}
override fun onDrawerOpened(drawerView: View) {
imm.hideSoftInputFromWindow(drawerView?.getWindowToken(), 0)
}
}
Put your action in the function you want to use. In my example, I'm closing the soft keyboard if the user interacts with the navigation drawer. Declare the InputMethodManager like this in your main activity:
var imm: InputMethodManager = this.getSystemService(Activity.INPUT_METHOD_SERVICE)
Add your custom DrawerListener to the drawerLayout (I put it in the onCreate method)
var drawerListener = CustomDrawer()
drawerLayout.addDrawerListener(drawerListener)