You need to enable JavaScript to run this app. Android TabLayout如何实现选中与未选中状态下标签字体大小切换
优惠活动
大模型
产品
解决方案
定价
更多

Android TabLayout如何实现选中与未选中状态下标签字体大小切换

实现TabLayout选中/未选中状态字体大小不同的方案

方案1:使用Material Components自带属性实现(推荐,无需额外代码)

你使用的是Material Design的TabLayout,1.1.0及以上版本的组件库已经原生支持分别设置选中、未选中状态的文本样式,操作步骤如下:

  • 首先创建两个不同的文本样式,分别对应选中和未选中状态:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 未选中状态的文本样式 -->
    <style name="MyCustomTabTextNormal">
        <item name="android:textSize">16sp</item>
        <!-- 可额外自定义未选中状态的文字颜色、字重等属性 -->
    </style>
    <!-- 选中状态的文本样式 -->
    <style name="MyCustomTabTextSelected">
        <item name="android:textSize">18sp</item>
        <!-- 可额外自定义选中状态的文字颜色、字重等属性 -->
    </style>
</resources>
  • 修改你的TabLayout布局代码,把原来单一的tabTextAppearance属性替换为分别设置选中、未选中样式的属性:
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/toolbar"
    android:overScrollMode="never"
    app:tabGravity="fill"
    app:tabMaxWidth="0dp"
    app:tabMode="scrollable"
    app:tabRippleColor="@null"
    app:tabIndicatorHeight="0dp"
    <!-- 替换为下方两个状态专属配置 -->
    app:tabTextAppearanceInactive="@style/MyCustomTabTextNormal"
    app:tabTextAppearanceActive="@style/MyCustomTabTextSelected"
    />

如果需要字体大小切换带有平滑过渡效果,可额外给TabLayout添加app:tabTextAnimationEnabled="true"属性,该属性默认值为true,不需要动画可设置为false关闭。

方案2:通过选中监听动态修改(兼容低版本库)

如果你使用的Material Components版本低于1.1.0,无法使用上述属性,可以通过监听Tab的选中状态动态修改字体大小,Kotlin代码示例如下:

tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    override fun onTabSelected(tab: TabLayout.Tab) {
        // 选中时放大字体,单位为sp
        tab.customView?.findViewById<TextView>(android.R.id.text1)?.textSize = 18f
    }

    override fun onTabUnselected(tab: TabLayout.Tab) {
        // 未选中时恢复默认字体大小,单位为sp
        tab.customView?.findViewById<TextView>(android.R.id.text1)?.textSize = 16f
    }

    override fun onTabReselected(tab: TabLayout.Tab) {}
})

// 页面初始化时默认给第一个选中Tab设置对应样式
tabLayout.getTabAt(0)?.let {
    it.customView?.findViewById<TextView>(android.R.id.text1)?.textSize = 18f
}

内容的提问来源于stack exchange,提问作者Leonard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 22:06:03