Design BottomNavigationView - 在代码中设置背景颜色

pro*_*m85 1 android android-support-library bottomnavigationview

有没有办法将BottomNavigationView代码中新设计库的背景颜色设置为自定义颜色值而不是颜色资源?任何"技巧"可能吗?

我目前的解决方案

  • 我让BottomNavigationView透明
  • 我在后面添加了第二个视图 bottomNavigationView
  • 我更新了这个视图的背景

但这看起来很丑陋,特别是因为我必须使用自定义行为为背景视图与BottomNavigationView父级中的CoordinatorLayout... 进行并行动画...

pro*_*m85 5

自己解决了.

解决方案1

我只是设置了透明背景的所有项目(这只需要一个资源文件),然后我主题BottomNavigationView实际背景本身.

bottomBar.setBackground(new ColorDrawable(color));
bottomBar.setItemBackgroundResource(R.drawable.transparent);
Run Code Online (Sandbox Code Playgroud)

资源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>
Run Code Online (Sandbox Code Playgroud)

解决方案2 - 通过反射(支持库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();
    }
}
Run Code Online (Sandbox Code Playgroud)