BottomNavigationView编程设置选中项背景颜色

3

我知道我们可以在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;
    };

但是对于我来说,它并没有起作用。有没有关于如何通过编程进行更改的想法或参考链接都会对我有所帮助。

注意:我只想更改所选项目的图标和文本色调,而不是底部导航中的所有项目。

提前感谢。

2个回答

4

您可以使用:

bottomNavigationView.setItemIconTintList(....)

并使用选择器(而非单一颜色):

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:alpha="1.0" android:color="@color/..." android:state_checked="true"/> 
  <item android:alpha="0.6" android:color="@color/..."/>
</selector>

enter image description here enter image description here

If you want to do it programmatically:

    int[][] states = new int[][] {
        new int[] { android.R.attr.state_checked}, // state_checked
        new int[] { }  // 
    };

    int[] colors = new int[] {
        color,
        color2
    };

    ColorStateList myColorList = new ColorStateList(states, colors);
    bottomNavigationView.setItemIconTintList(myColorList);

1
我尝试过这个,但它影响了底部导航中的所有项目。我只想更改所选的那一个。 - Sneha Mudhigonda
@SnehaMudhigonda 这是因为您没有使用选择器。 - Gabriele Mariotti
是的,我用过那个,但是如何在程序中动态更改可绘制对象的颜色呢? - Sneha Mudhigonda
使用 setItemTextColor 来设置文本颜色,使用 setItemIconTintList 来设置图标。 - Gabriele Mariotti
这个有更新了吗? - Moustafa EL-Saghier
显示剩余2条评论

-1

这是@Gabriel在Kotlin中的答案:

val states = arrayOf(
                intArrayOf(android.R.attr.state_checked),
                intArrayOf()
            )
    
val colors = intArrayOf(
                selectedColor,
                unselectedColor
            )

val myColorStateList = ColorStateList(states, colors)
bottomNavigationView.itemIconTintList = myColorStateList
bottomNavigationView.itemTextColor = myColorStateList

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接