The first thing that I am mentioning is, onBackpressed() is deprecated in the activity scope. And I am facing the problem of closing the drawer layout onthe back button click. I am using the jetpack navigation component. When I click to the hamburger icon, the drawer is opening. After that if I click the back button it should close drawer first then the second time should exit the app but it's not closing the drawer.Without close the drawer app exits on first-time back button clicks. Now I want such behavior that while the drawer is open, it should close first when I click the back button of the device.
I am using single activity pattern and jetpack navigation ui components. My codes are right below
// jetpack navigation with kotlin
def nav_version = "2.6.0-alpha01"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
and this is the codes in my Mainactivity.kt
class MainActivity : AppCompatActivity() {
private val binding by viewBinding(ActivityMainBinding::inflate)
lateinit var controller: NavController
lateinit var config: AppBarConfiguration
lateinit var listener: NavController.OnDestinationChangedListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
//set the toolbar as default action bar
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
//set the toolbar with navigation graph
val host = supportFragmentManager
.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
controller = host.navController
config = AppBarConfiguration(controller.graph, binding.drawerLayout)
setupActionBarWithNavController(controller, config)
//set navview to navcontroller
binding.navView.setupWithNavController(controller)
//nav listener
listener = NavController
.OnDestinationChangedListener { controller, destination, arguments ->}
}
override fun onSupportNavigateUp(): Boolean {
return controller.navigateUp(config) || super.onSupportNavigateUp()
}
override fun onResume() {
super.onResume()
controller.addOnDestinationChangedListener(listener)
}
override fun onPause() {
super.onPause()
controller.removeOnDestinationChangedListener(listener)
}
}