Reputation: 17798
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:
BottomNavigationView
transparentbottomNavigationView
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
...
Upvotes: 1
Views: 7736
Reputation: 776
After many search, only this resolve my case:
bottomNavigationView.setItemBackground(new ColorDrawable(color));
Here I set each one of background item.
Upvotes: 0
Reputation: 17798
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();
}
}
Upvotes: 8