上代码:
public static void setTabWidth(final TabLayout tabLayout, final int padding){
tabLayout.post(new Runnable() {
@Override
public void run() {
try {
//拿到tabLayout的mTabStrip属性
LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
View tabView = mTabStrip.getChildAt(i);
//拿到tabView的mTextView属性 tab的字数不固定一定用反射取mTextView
Field mTextViewField = tabView.getClass().getDeclaredField(“mTextView”);
mTextViewField.setAccessible(true);
TextView mTextView = (TextView) mTextViewField.get(tabView);
tabView.setPadding(0, 0, 0, 0);
//因为我想要的效果是 字多宽线就多宽,所以测量mTextView的宽度
int width = 0;
width = mTextView.getWidth();
if (width == 0) {
mTextView.measure(0, 0);
width = mTextView.getMeasuredWidth();
}
//设置tab左右间距 注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
params.width = width ;
params.leftMargin = padding;
params.rightMargin = padding;
tabView.setLayoutParams(params);
tabView.invalidate();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
}
效果图如下:
提醒:这种方式改变Indicator最短也就Tab内容的宽度,如果设置很短,Tab内容就显示不下,如下图:
二、通过TabLayout setCustomView 的方式
第一种通过反射的方式设置Indicator宽度,最短只能Tab内容的宽度,如果设计师要所有选中的Tab下的Indicator都设置一个指定的宽度,这种就不行了。TabLayout可以设置自定义View,可以通过这种方法来达到目的。
1, 将TabLayout 的tabIndicatorHeight 设置为0
2,通过TabLayout 的setCustomView方式添加Tab
3, 在onTabSelected 回调种,处理Tab选中和未选中的状态;
4,为了方便使用,封装成一个通用的View
首先看布局: enhance_tab_layout.xml
:
<android.support.design.widget.TabLayout
android:id=“@+id/enhance_tab_view”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
app:tabIndicatorHeight=“0dp”
</android.support.design.widget.TabLayout>
Tab item 布局:tab_item_layout.xml
如上,TextView显示Tab内容,下面的View就是Tab下面的Indicator(下划线)。 自己定义的View,宽度随便你改。
添加Tab的时候使用setCustomView 方法:
/**
- 添加tab
- @param tab
*/
public void addTab(String tab){
mTabList.add(tab);
View customView = getTabView(getContext(),tab,mIndicatorWidth,mIndicatorHeight,mTabTextSize);
mCustomViewList.add(customView);
mTabLayout.addTab(mTabLayout.newTab().setCustomView(customView));
}
/**
- 获取Tab 显示的内容
- @param context
- @para