Skip to content

Instantly share code, notes, and snippets.

@Pulimet
Last active Dec 26, 2019
Embed
What would you like to do?
Navigation component + ToolBar + Drawer (Navigation icon click behavior and animation fix)
private var navController: NavController? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setNavigationAndToolBar()
}
private fun setNavigationAndToolBar() {
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
navController = findNavController(R.id.nav_host_fragment)
navController?.let { navController ->
// The set of destinations by id considered at the top level of your information hierarchy.
// The Up button will not be displayed when on these destinations.
appBarConfiguration = AppBarConfiguration(
setOf(R.id.splashFragment, R.id.homeFragment),
drawerLayout
)
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration!!)
}
fixNavigationIconBehavior()
setDrawerListener()
}
private fun fixNavigationIconBehavior() {
toolbar.setNavigationOnClickListener {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
if ((toolbar.navigationIcon as DrawerArrowDrawable).progress == 1.0f) {
navController?.navigateUp()
} else {
drawerLayout.openDrawer(GravityCompat.START)
}
}
}
}
private fun setDrawerListener() {
drawerLayout.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() {
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
toolbar.navigationIcon as DrawerArrowDrawable).progress = slideOffset
}
})
}
override fun onBackPressed() {
when {
drawerLayout.isDrawerOpen(GravityCompat.START) -> drawerLayout.closeDrawer(GravityCompat.START)
else -> super.onBackPressed()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment