I have implemented Navigation Drawer in android.
Working fine.
onBackPressed method is also implemented.
Working fine.
Now, I want same onBackPressed() method's functionality on Back Button click of Navigation Drawer. (Back Button is set in Navigation Drawer.)
I have set Back Arrow button as below :
// Set back button
mFragmentManager.addOnBackStackChangedListener(FragmentManager.OnBackStackChangedListener {
if (mFragmentManager.backStackEntryCount > 0) {
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
} else {
supportActionBar!!.setDisplayHomeAsUpEnabled(false)
mToggle.syncState()
}
})
Now, to take the click of Back button I have implemented below method :
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home-> {
Toast.makeText(this, "Back pressed", Toast.LENGTH_SHORT)
.show();
onBackPressed();
}
}
return super.onOptionsItemSelected(item)
}
But, this toast inside is not displaying, instead it just opening my Navigation Drawer.
What might be the issue ? Thanks.
EDIT :
Below is the code to open Drawer i.e. as below :
mToggle = ActionBarDrawerToggle(
this,
mDrawer,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
mDrawer.addDrawerListener(mToggle)
mToggle.syncState()
Here, just set a ActionBarDrawerToggle to Navigation Drawer. So, Drawer open when I click on HumberIcon.
Below is the onBackPressed() method inside my Activity :
if (mDrawer.isDrawerOpen(GravityCompat.START)) {
mDrawer.closeDrawer(GravityCompat.START)
} else {
if (mFragmentManager.backStackEntryCount > 0) {
mFragmentManager.popBackStack()
nav_view.setCheckedItem(R.id.nav_home_fragment)
} else {
if (mFragmentManager.findFragmentById(R.id.fragment_container) is SecondFragment) {
mFragmentManager.popBackStack()
nav_view.setCheckedItem(R.id.nav_home_fragment)
} else {
super.onBackPressed()
}
}
}
}