mTabTop.post(new Runnable() {
@Override
public void run() {
TabIndicatorUtils.setIndicator(mTabTop, DisplayUtils.sp2px(getActivity(), 16));
}
});
import android.graphics.Paint;
import android.support.design.widget.TabLayout;
import android.view.View;
import android.widget.LinearLayout;
import java.lang.reflect.Field;
/**
* Created by Administrator on 2018/7/31.
*/
public class TabIndicatorUtils {
/**
* 修改TabLayout的下划线长度
* 单位px
*/
public static void setIndicator(TabLayout tabs, int textSize) {
Paint paint = new Paint();
paint.setTextSize(textSize);
float textWidth = paint.measureText((String) tabs.getTag());
int padding = (int) ((tabs.getWidth() / tabs.getTabCount() - textWidth) / 2);
Class<?> tabLayout = tabs.getClass();
Field tabStrip = null;
try {
tabStrip = tabLayout.getDeclaredField("mTabStrip");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
tabStrip.setAccessible(true);
LinearLayout llTab = null;
try {
llTab = (LinearLayout) tabStrip.get(tabs);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
for (int i = 0; i < llTab.getChildCount(); i++) {
View child = llTab.getChildAt(i);
child.setPadding(0, 0, 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
params.leftMargin = padding;
params.rightMargin = padding;
child.setLayoutParams(params);
child.invalidate();
}
}
}
<android.support.design.widget.TabLayout
android:id="@+id/tabtop"
android:layout_width="220dp"
android:layout_height="match_parent"
android:background="@color/CN36"
android:tag="1哈哈哈"
app:tabIndicatorColor="@color/white"
app:tabIndicatorHeight="2dp"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/white"
app:tabTextAppearance="@style/TabLayoutTextHomeStyle"
app:tabTextColor="@drawable/selector_text_choice_white" />
因为Tablayout每个字tab的宽度是一致的,所以需要根据子tab里最长的文字进行设置下划线的长度。xml里面的tag就是设置的最长tab的文字。
tabMode需要设置fixed。
tab间距根据控件总长度以及最长文字的宽度计算。