Reputation: 185
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.
Upvotes: 4
Views: 6021
Reputation: 271
Here is @Gabriel's answer in 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
Upvotes: 0
Reputation: 363667
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>
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);
Upvotes: 6