After many hours of trying to make the text gradient, I was finally able to achieve this effect. The point is to reach the MaterialTextView inside BottomNavigationItemView
. This is the code I use in onCreate()
method of the activity (Kotlin):
for (bottomNavigationItem in binding.bottomNavigation[0] as BottomNavigationMenuView) {
(((bottomNavigationItem as BottomNavigationItemView)
.getChildAt(1) as BaselineLayout)
.getChildAt(1) as MaterialTextView)
.setGradientText()
}
setGradientText() method simply decorates text. In your case you need to add third color and setup angle:
fun MaterialTextView.setGradientText() {
paint.shader = LinearGradient(
0f,
0f,
paint.measureText(text.toString()),
textSize,
intArrayOf(
ContextCompat.getColor(context, R.color.main_gradient_start),
ContextCompat.getColor(context, R.color.main_gradient_end)
),
null, Shader.TileMode.CLAMP
)
}
This code will decorate every element in bottom navigation and they only will be gradient when the element is selected. I'm not sure if it is possible to make gradient work on active and inactive elements at the same time.
Also, if you need code of my BottomNavigationView
:
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNavigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/black"
app:itemTextColor="@drawable/bottom_menu_selector"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="@menu/bottom_menu" />
In conclusion, this is the best result I've reached now:
Gradient text
About icons: you need to create selectors for your icons and add them to your menu file like this:
Sample selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Icon active gradient -->
<item android:drawable="@drawable/ic_home_color" android:state_pressed="true"/>
<item android:drawable="@drawable/ic_home_color" android:state_checked="true"/>
<!-- Icon default -->
<item android:drawable="@drawable/ic_home"/>
</selector>
Menu file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/home"
android:icon="@drawable/home_selector"
android:title="@string/home" />
<item
android:id="@+id/catalogue"
android:icon="@drawable/catalogue_selector"
android:title="@string/catalogue" />
<item
android:id="@+id/collections"
android:icon="@drawable/collections_selector"
android:title="@string/collections" />
<item
android:id="@+id/profile"
android:icon="@drawable/profile_selector"
android:title="@string/profile" />
</menu>