prom85 prom85 - 1 month ago 14
Android Question

Design BottomNavigationView - set background color in code

Is there any way to set the background color of the new design libraries

BottomNavigationView
in code to a custom color value instead of a color resource? Any "trick" maybe?

My current solution:


  • I make the
    BottomNavigationView
    transparent

  • I add a second view behind the
    bottomNavigationView

  • I update this view's background



But this looks ugly, especially as I have to use a custom behaviour for the background view to be animated in parallel with the
BottomNavigationView
in the parent
CoordinatorLayout
...

Answer

Solved it myself.

Solution 1

I just setup all items with a transparent background (this needs one resource file only) and then I theme the BottomNavigationView actual background itself.

bottomBar.setBackground(new ColorDrawable(color));
bottomBar.setItemBackgroundResource(R.drawable.transparent);

Resource drawable - transparent.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@android:color/transparent" />
</shape>

Solution 2 - via reflection (support library 25.0.0)

public void themeBottomBarBackgroundWithReflection(BottomNavigationView bottomBar, int color)
{
    try
    {
        Field mMenuViewField = BottomNavigationView.class.getDeclaredField("mMenuView");
        mMenuViewField.setAccessible(true);
        BottomNavigationMenuView mMenuView = (BottomNavigationMenuView)mMenuViewField.get(bottomBar);
        Field mButtonsField = BottomNavigationMenuView.class.getDeclaredField("mButtons");
        mButtonsField.setAccessible(true);
        BottomNavigationItemView[] mButtons = (BottomNavigationItemView[])mButtonsField.get(mMenuView);

        for (BottomNavigationItemView item : mButtons) {
            ViewCompat.setBackground(item, new ColorDrawable(color));
        }
    }
    catch (NoSuchFieldException e)
    {
        e.printStackTrace();
    }
    catch (IllegalAccessException e)
    {
        e.printStackTrace();
    }
}