原文链接:https://blog.youkuaiyun.com/qq_15736263/article/details/80972691
网上很多博客TabLayout定义下标宽度都是通过反射修改Tab的宽度实现的,实际效果就是Tab的点击范围变小,且这种方法下标最短宽度只能设置成最宽的Tab的宽度,体验效果很不好。
查看源码后发现 其实就是在draw方法中画了一条长方体,包括动画也是这样实现的。
public void draw(Canvas canvas) { super.draw(canvas); if (this.mIndicatorLeft >= 0 && this.mIndicatorRight > this.mIndicatorLeft) { canvas.drawRect((float)this.mIndicatorLeft, (float)(this.getHeight() - this.mSelectedIndicatorHeight), (float)this.mIndicatorRight, (float)this.getHeight(), this.mSelectedIndicatorPaint); } }
那我们明白了,只需要修改这个长方体的左右坐标即可。
修改完成后代码如下
public void draw(Canvas canvas) { super.draw(canvas); if (this.mIndicatorLeft >= 0 && this.mIndicatorRight > this.mIndicatorLeft) { if (this.mSelectedIndicatorWidth <= 0) { canvas.drawRect((float)this.mIndicatorLeft, (float)(this.getHeight() - this.mSelectedIndicatorHeight), (float)this.mIndicatorRight, (float)this.getHeight(), this.mSelectedIndicatorPaint); } else { int left = (this.mIndicatorRight - this.mIndicatorLeft) / 2 - this.mSelectedIndicatorWidth / 2 + this.mIndicatorLeft; canvas.drawRect((float)left, (float)(this.getHeight() - this.mSelectedIndicatorHeight), (float)(left + this.mSelectedIndicatorWidth), (float)this.getHeight(), this.mSelectedIndicatorPaint); } } }
其实很简单,就是不知道Google为啥不愿意去实现,只能我们自己加代码实现了
为了方便伸手党,代码已经上传到了github
地址:https://github.com/MoonlitDropOfBlood/TabLayout
盗链的各位爸爸,麻烦留个源链接吧,拜托了