我知道我们可以在XML中以这种方式设置底部导航选项的颜色。
但是我想知道如何从我的 Activity 中以编程方式进行更改?
以下是我在 Activity 的 OnNavigationItemSelectedListener
中尝试过的代码:
item.getIcon().setTint(ContextCompat.getColor(context, R.color.colorBrown));
我也尝试像这样更改色调列表:
item.setIconTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.colorPrimaryBlue)));
这是我的代码完整片段:
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= item -> {
switch (item.getItemId()) {
case R.id.navigationTask:
item.getIcon().setTint(ContextCompat.getColor(context, R.color.colorBrown));
fragment = new MyTaskFragment();
break;
case R.id.navigationProfile:
item.setIconTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.colorPrimaryBlue)));
fragment = new ProfileFragment();
break;
case R.id.navigationRequest:
fragment = new RequestListFragment();
break;
case R.id.navigationMore:
fragment = new MoreFragment();
break;
}
loadFragment(fragment);
return true;
};
但是对于我来说,它并没有起作用。有没有关于如何通过编程进行更改的想法或参考链接都会对我有所帮助。
注意:我只想更改所选项目的图标和文本色调,而不是底部导航中的所有项目。
提前感谢。
setItemTextColor
来设置文本颜色,使用setItemIconTintList
来设置图标。 - Gabriele Mariotti