Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose menu #11

Closed
wants to merge 2 commits into from
Closed

Expose menu #11

wants to merge 2 commits into from

Conversation

RankoR
Copy link

@RankoR RankoR commented Oct 14, 2019

Menu has to be exposed for correct integration with navigation.

For example, now you can use this code for correct bottom nav switching on fragment change in AndroidX navigation:

internal fun matchDestination(destination: NavDestination, @IdRes destId: Int): Boolean {
    var currentDestination: NavDestination
    currentDestination = destination

    while (currentDestination.id != destId && currentDestination.parent != null) {
        currentDestination = currentDestination.parent as NavDestination
    }

    return currentDestination.id == destId
}

fun setupWithNavController(
    bottomNavigationView: ChipNavigationBar,
    navController: NavController
) {
    var selectedItemId = -1

    bottomNavigationView.setOnItemSelectedListener { itemId ->
        if (itemId != selectedItemId) {
            navController.navigate(itemId, null, null)
        }
    }

    val weakReference = WeakReference(bottomNavigationView)

    navController.addOnDestinationChangedListener(object :
        NavController.OnDestinationChangedListener {
        override fun onDestinationChanged(
            controller: NavController,
            destination: NavDestination,
            arguments: Bundle?
        ) {
            val view = weakReference.get()
            if (view == null) {
                navController.removeOnDestinationChangedListener(this)
            } else {
                view.menu?.let { menu ->
                    var h = 0

                    val size = menu.items.size
                    while (h < size) {
                        val item = menu.items[h]
                        if (matchDestination(destination, item.id)) {
                            view.setItemSelected(item.id)
                            selectedItemId = item.id
                        }

                        ++h
                    }
                }
            }
        }
    })
}

Note: menu items' ids must match navigation fragment ids.

@ismaeldivita
Copy link
Owner

ismaeldivita commented Oct 24, 2020

Close since #20 is being tackled

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants