设置app:tabIndicator自定义Drawable后TabLayout在三星S7上不可见
问题根因
三星Galaxy S7搭载的是Android 6.0/7.0系统,这类低版本三星系统的Drawable渲染逻辑和原生AOSP存在差异,结合旧版Material Components库的TabLayout实现bug,会导致XML中配置的自定义指示器Drawable测量异常,最终TabLayout宽高被计算为0、完全不可见,而Nexus 5X用的是原生Android系统,不存在该渲染差异,所以运行正常。
解决方案
- 方案1:给自定义Drawable显式指定宽高,避免系统自动测量出错
给你的shop_item_tab.xml新增size标签,代码如下:<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/blue"/> <corners android:radius="5dp"/> <!-- 宽和你配置的tabMaxWidth一致,高按需设置指示器高度即可 --> <size android:width="16dp" android:height="2dp"/> </shape> - 方案2:代码动态设置指示器Drawable,避开XML解析的兼容问题
先删除布局里app:tabIndicator="@drawable/shop_item_tab"这行配置,在页面初始化阶段通过代码设置:// Kotlin示例 val indicator = ContextCompat.getDrawable(context, R.drawable.shop_item_tab) tl_shop_item.setSelectedTabIndicator(indicator)// Java示例 Drawable indicator = ContextCompat.getDrawable(context, R.drawable.shop_item_tab); tl_shop_item.setSelectedTabIndicator(indicator); - 方案3:升级Material Components依赖版本
1.4.0及以上版本的Material库已经修复了该类三星设备TabLayout兼容bug,建议升级到最新稳定版:implementation 'com.google.android.material:material:1.9.0' - 方案4:兜底配置避免测量失效
给TabLayout新增最小宽高属性,避免测量异常导致组件完全消失:<com.google.android.material.tabs.TabLayout ...其他原有属性 android:minWidth="40dp" android:minHeight="16dp"/>
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

