Skip to content

Instantly share code, notes, and snippets.

@Pulimet
Last active December 26, 2019 17:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pulimet/7179a66f2fbde2bad9a25235829501bb to your computer and use it in GitHub Desktop.
Save Pulimet/7179a66f2fbde2bad9a25235829501bb to your computer and use it in GitHub Desktop.
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