Instantly share code, notes, and snippets.
Last active
December 26, 2019 17:37
Navigation component + ToolBar + Drawer (Navigation icon click behavior and animation fix)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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