有没有办法将BottomNavigationView
代码中新设计库的背景颜色设置为自定义颜色值而不是颜色资源?有什么“技巧”吗?
我目前的解决方案:
- 我让
BottomNavigationView
透明 - 我在后面添加了第二个视图
bottomNavigationView
- 我更新了这个视图的背景
但这看起来很难看,特别是因为我必须使用自定义行为来使背景视图与BottomNavigationView
父级中的动画并行CoordinatorLayout
...
有没有办法将BottomNavigationView
代码中新设计库的背景颜色设置为自定义颜色值而不是颜色资源?有什么“技巧”吗?
我目前的解决方案:
BottomNavigationView
透明bottomNavigationView
但这看起来很难看,特别是因为我必须使用自定义行为来使背景视图与BottomNavigationView
父级中的动画并行CoordinatorLayout
...
自己解决了。
解决方案 1
我只是将所有项目设置为透明背景(这只需要一个资源文件),然后我为BottomNavigationView
实际背景本身设置主题。
bottomBar.setBackground(new ColorDrawable(color));
bottomBar.setItemBackgroundResource(R.drawable.transparent);
资源可绘制 - 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>
解决方案 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();
}
}
经过多次搜索,只有这样才能解决我的情况:
bottomNavigationView.setItemBackground(new ColorDrawable(color));
这里我设置了每一个背景项目。