Just upgraded my application to Material Components 1.1.0 and the icons in my TabLayout no longer display. I followed the tutorial on the official website of google material.io, the preview in Android Studio is good, but once the application is launched, the icons do not appear.
Here is the XML Code :
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_gravity="bottom"
style="@style/Widget.MaterialComponents.TabLayout.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="center">
<com.google.android.material.tabs.TabItem
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:icon="@drawable/ic_home"/>
<com.google.android.material.tabs.TabItem
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:icon="@drawable/ic_fav"/>
<com.google.android.material.tabs.TabItem
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:icon="@drawable/ic_about"/>
</com.google.android.material.tabs.TabLayout>
</androidx.viewpager.widget.ViewPager>
</RelativeLayout>
In my styles.xml file I defined colorPrimary and colorOnPrimary which are used to tint icons and TabLayout background color.
However, even if the preview in Android Studio is good, once the application is launched, the background of my TabLayout is displayed in the right color, but the icons don't show up.
EDIT :
Just use debug mode and icon of tabs are null for each tab item :
EDIT 2:
I have found the problem but not the solution! The problem comes from this line :
tabLayout.setupWithViewPager(viewPager)
After this line is executed, all icons in TabLayout are reset to null. By disabling this line I have all of my icons. However, how can i setup a ViewPager with icons on my TabLayout ? If I set them up manually, I will not have the color inherited from MDC
The method tabLayout.setupWithViewPager()
removes all tabs and then adds tabs from the adapted.
To add the icons you can use something like:
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setIcon(iconResId);
}
If I set them up manually, I will not have the color inherited from MDC
The com.google.android.material.tabs.TabLayout
uses by default the Widget.MaterialComponents.TabLayout
style. If you want to override the icon tint just use tabIconTint
in your layout or custom style:
<com.google.android.material.tabs.TabLayout
app:tabIconTint="@color/my_selector"
...>