刚刚将我的应用程序升级到材料组件1.1.0,我的TabLayout中的图标不再显示。我在google material.io的官方网站上学习了教程,Android的预览效果很好,但是一旦应用程序启动,图标就不会出现。
下面是XML代码:
<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>
在我的styles.xml文件中,我定义了colorPrimary和colorOnPrimary,它们用于着色图标和TabLayout背景色。
但是,即使Android中的预览效果很好,一旦应用程序启动,我的TabLayout的背景就会以正确的颜色显示,但是图标不会显示出来。
编辑:
只需使用调试模式,每个选项卡的图标为null:
编辑2:
我找到了问题,但没有找到解决办法!问题来自于这一行:
tabLayout.setupWithViewPager(viewPager)
在执行这一行之后,TabLayout中的所有图标都被重置为null。通过禁用这一行,我有我所有的图标。但是,如何在我的ViewPager上设置带有图标的TabLayout?如果手动设置它们,则不会从MDC继承颜色。
发布于 2020-06-01 15:06:07
方法tabLayout.setupWithViewPager()
移除所有制表符,然后从适配的选项卡中添加制表符。
要添加图标,可以使用以下内容:
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setIcon(iconResId);
}
如果手动设置
,则不会从MDC继承颜色。
默认情况下,com.google.android.material.tabs.TabLayout
使用Widget.MaterialComponents.TabLayout
样式。如果要覆盖图标色调,只需在布局或自定义样式中使用tabIconTint
:
<com.google.android.material.tabs.TabLayout
app:tabIconTint="@color/my_selector"
...>
https://stackoverflow.com/questions/62129757
复制相似问题