TabLayout搭配ViewPager用起来的确很爽,尴尬的是官方没有提供修改下划线长度的方法。造成了下划线长度和item的宽一样长。百度找到网上的方案,通过反射修改每个Item的Margin,Item变小了,随之下划线就变短了。尴尬的是当Item个数比较多而且Title字数较多的时候,文字就会换行。反射方法原文
最终解决方法:
1.先把TabLayout源码下来
2.在TabLayout中找到SlidingTabStrip的draw()方法
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
// Thick colored underline below the current selection
if (mIndicatorLeft >= 0 && mIndicatorRight > mIndicatorLeft) {
canvas.drawRect(mIndicatorLeft, getHeight() - mSelectedIndicatorHeight,
mIndicatorRight, getHeight(), mSelectedIndicatorPaint);
}
}
3.计算好下划线左右两边的边距
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (mIndicatorLeft >= 0 && mIndicatorRight > mIndicatorLeft) {
canvas.drawRect(mIndicatorLeft+dpToPx(25), getHeight() - mSelectedIndicatorHeight,
mIndicatorRight-dpToPx(25), getHeight(), mSelectedIndicatorPaint);
}
}
最终效果如下:
说明:下划线左右边距可以计算一次然后记录下来,避免浪费CPU资源。