Skip to content

Instantly share code, notes, and snippets.

@0rp3u
Created March 18, 2020 20:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0rp3u/c3fa487cb20e9ff81c05cc386fb54455 to your computer and use it in GitHub Desktop.
Save 0rp3u/c3fa487cb20e9ff81c05cc386fb54455 to your computer and use it in GitHub Desktop.
setup bottomNav with custom default destination
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.annotation.IdRes
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.NavOptions
import androidx.navigation.ui.R
import com.google.android.material.bottomnavigation.BottomNavigationView
import java.lang.ref.WeakReference
private fun matchDestination(
destination: NavDestination,
@IdRes destId: Int
): Boolean {
var currentDestination: NavDestination? = destination
while (currentDestination!!.id != destId && currentDestination.parent != null) {
currentDestination = currentDestination.parent
}
return currentDestination.id == destId
}
private fun onNavDestinationSelected(
@IdRes baseDestinationId: Int,
item: MenuItem,
navController: NavController
): Boolean {
val builder = NavOptions.Builder()
.setLaunchSingleTop(true)
.setEnterAnim(R.anim.nav_default_enter_anim)
.setExitAnim(R.anim.nav_default_exit_anim)
.setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
.setPopExitAnim(R.anim.nav_default_pop_exit_anim)
if (item.order and Menu.CATEGORY_SECONDARY == 0) {
builder.setPopUpTo(baseDestinationId, false)
}
val options = builder.build()
return try { //TODO provide proper API instead of using Exceptions as Control-Flow.
navController.navigate(item.itemId, null, options)
true
} catch (e: IllegalArgumentException) {
false
}
}
fun BottomNavigationView.setupWithNavController(
@IdRes baseDestinationId: Int,
navController: NavController
) {
setOnNavigationItemSelectedListener { item -> onNavDestinationSelected(baseDestinationId, item, navController) }
val weakReference = WeakReference(this)
navController.addOnDestinationChangedListener(object : NavController.OnDestinationChangedListener {
override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) {
val view = weakReference.get()
if (view == null) {
navController.removeOnDestinationChangedListener(this)
return
}
val menu = view.menu
(0 until menu.size()).forEach {
val item = menu.getItem(it)
if (matchDestination(destination, item.itemId)) {
item.isChecked = true
}
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment