Android 中如何实现 TabLayout 的 tab 文字左对齐
要实现 TabLayout 内部 tab 文字左对齐,有两种常用实现方案:
方法一:自定义Tab项布局(灵活度最高,支持更多自定义样式)
- 首先创建自定义tab布局文件
res/layout/item_tab_custom.xml:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical|start" android:textSize="14sp" android:textColor="@color/design_default_color_primary" />
- 在代码中为每个Tab设置自定义视图:
val tabLayout = findViewById<TabLayout>(R.id.tabs) // 遍历已有Tab设置自定义布局和文字 for (i in 0 until tabLayout.tabCount) { val tab = tabLayout.getTabAt(i) ?: continue tab.setCustomView(R.layout.item_tab_custom) (tab.customView as TextView).text = tab.text } // 动态新增Tab时也可以直接设置自定义布局 tabLayout.addTab( tabLayout.newTab() .setCustomView(R.layout.item_tab_custom) .setText("Tab1")
方法二:自定义文本样式实现(无需额外布局,修改更简单)
- 在
res/values/styles.xml中新增Tab文字样式:
<style name="TabLeftAlignText" parent="TextAppearance.MaterialComponents.Tab"> <item name="android:gravity">start|center_vertical</item> <item name="android:textAlignment">viewStart</item> </style>
- 将样式添加到你的TabLayout布局中即可,修改后代码如下:
<com.google.android.material.tabs.TabLayout android:id="@+id/tabs" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/holo_green_dark" app:tabMode="scrollable" app:tabTextAppearance="@style/TabLeftAlignText" <!-- 可选:调整Tab内边距避免文字贴边 app:tabPaddingStart="16dp" app:tabPaddingEnd="16dp" --> />
注意事项
- 如果需要Tab宽度可以通过
app:tabMinWidth和app:tabMaxWidth设置为相同值即可 - 不要设置
app:tabGravity="fill"属性,会导致布局撑开后对齐效果失效
内容的提问来源于stack exchange,提问作者Roman
相关产品推荐
相关产品推荐

