} 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
- @param
- @return
*/
public static View getTabView(Context context,String text,int indicatorWidth,int indicatorHeight,int textSize) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_item_layout, null);
TextView tabText = (TextView) view.findViewById(R.id.tab_item_text);
if(indicatorWidth>0){
View indicator = view.findViewById(R.id.tab_item_indicator);
ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams();
layoutParams.width = indicatorWidth;
layoutParams.height = indicatorHeight;
indicator.setLayoutParams(layoutParams);
}
tabText.setTextSize(textSize);
tabText.setText(text);
return view;
}
然后在onTabSelected中处理状态:
@Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
EnhanceTabLayout mTabLayout = mTabLayoutRef.get();
if(mTabLayoutRef!=null){
List customViewList = mTabLayout.getCustomViewList();
if(customViewList == null || customViewList.size() ==0){
return;
}
for (int i=0;i<customViewList.size();i++){
View view = customViewList.get(i);
if(view == null){
return;
}
TextView text = (TextView) view.findViewById(R.id.tab_item_text);