Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BottomNavigationView set selected item background color programmatically

I know we can set the bottom navigation selection color from XML in this way

But I want to know how we can change it programmatically from my Activity?

This is what I tried in Activity's OnNavigationItemSelectedListener.

 item.getIcon().setTint(ContextCompat.getColor(context, R.color.colorBrown));

Also tried to change tint list like this:

item.setIconTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.colorPrimaryBlue)));

Here is the complete snippet of my code:

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;
    };

but it's not working for me. Any ideas or reference link on how to change this programmatically will be helpful for me.

Note: I want to change only the selected item's icon and text tint color. Not the entire items in the bottom navigation.

Thanks in advance.

like image 881
Sneha Mudhigonda Avatar asked Oct 25 '25 04:10

Sneha Mudhigonda


1 Answers

You can use:

bottomNavigationView.setItemIconTintList(....)

and use a selector (not a single color):

<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);
like image 166
Gabriele Mariotti Avatar answered Oct 26 '25 16:10

Gabriele Mariotti