Search code examples
androidandroid-layoutandroidxbottomnavigationview

BottomNavigationView layout broken, when add menu items programmatically


For some reason BottomNavigationView has a visual bug in layout. Does anyone know any way to fix it? The problem resolves after any button is clicked or after I minimize app and restore it.

This is how it is supposed to look:

Everything works when menu is inflated via XML.

<com.google.android.material.bottomnavigation.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="56dp"
        ...
        app:menu="@menu/bottom_navigation_4_game" />

Correct

When I added MenuItem programmatically:

navigationView.menu.clear()
navigationView.inflateMenu(R.menu.bottom_navigation4)

Incorrect

We may see in LayoutInspector, that there are actually 5 items, but two of them are overlayed and not seen:

LayoutInspector

The problem is probably in BottomNavigationMenuView. In LayoutInspector getWidth() returns 0. Invalidating views didn't help. width is 0


Solution

  • I found a weird code block in the app, that was to blame. Turns out, that TransitionManager didn't end its transitions with ConstraintLayout. This code: updateConstraints {} was called immediately after dynamically changing BottomNavigationView, hence its child views transition was interrupted, I guess.

    private fun updateConstraints(f: ConstraintSet.() -> Unit) {
        TransitionManager.beginDelayedTransition(root)
        val set = ConstraintSet().apply { clone(root) }
        set.f()
        set.applyTo(root)
    }