效果
红色标注是不同的间距。
实现方式
1、xml中定义
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="wrap_content"
app:tabIndicatorColor="@color/color_FF00B2E3"
app:tabBackground="@android:color/transparent"
app:tabRippleColor="@android:color/transparent"
android:layout_height="wrap_content"
app:tabIndicatorHeight="5dp"
android:background="@android:color/transparent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</com.google.android.material.tabs.TabLayout>
2、代码动态添加自定义tab
for (int i = 0; i < mTabsStrId.length; i++) {
View tabview = LayoutInflater.from(getContext()).inflate(R.layout.tab_item, null);
TextView tvTab = tabview.findViewById(R.id.tv_tab);
tvTab.setText(mTabsStrId[i]);
TabLayout.Tab tab = binding.tabLayout.newTab();
tab.setCustomView(tabview);
binding.tabLayout.addTab(tab, i == 0);
}
tab的xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:includeFontPadding="false"
android:textFontWeight="500"
android:text="@string/xxx"
android:textColor="@color/selector_xxx"
android:textSize="28sp" />
</LinearLayout>
3、去除tablayout原有padding,并设置两个tab之间的间距
for (int i = 0; i < binding.tabLayout.getTabCount(); i++) {
View tab = ((ViewGroup) binding.tabLayout.getChildAt(0)).getChildAt(i);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
tab.setPadding(0, 0, 0, 0);
if (i > 0) {
params.setMargins(DisplayUtils.dp2px(86), 0, 0, 0); // 设置左右间距
} else {
params.setMargins(DisplayUtils.dp2px(22), 0, 0, 0); // 设置左右间距
}
}
binding.tabLayout.invalidate();