github地址:https://github.com/shallcheek/CaterpillarIndicator
偶然看到在微博的最新版本看到发现界面和个人界面的几个Tab滑动的指示器添加了动画,看起来比以前的线条滑动看起来生动些。
实现滑动是我们Android开发经常运用到的ViewPage 线条的滑动则是根据ViewPage 的Select Item 标识决定的。而相应的滑动动画效果则是根据ViewPage的监听事件OnPageChangeListener 中对应的回调方法
public void onPageScrolled(int position,float positionOffset,int positionOffsetPixels)positionOffsetPixels是滑动距离,和屏幕有关,*手指往左滑动,该值递增,反之递减 对应的可以判断左右滑动然后根据值对线条做相应的处理
计算出的的scroll_x则是线条的左右滑动距离 线条往左边移动是负数往右边是正数 所以线条长短变化实现代码如下:
//获取单个item线条的宽度 不能超过View的宽度平分的宽度 this.mItemLineWidth = mItemLineWidth > cursorWidth ? cursorWidth : mItemLineWidth; int mItemLeft; int mItemRight; if (mItemLineWidth < cursorWidth) { mItemLeft = (cursorWidth - mItemLineWidth) / 2; mItemRight = cursorWidth - mItemLeft; } else { mItemLeft = 0; mItemRight = cursorWidth; } boolean isHalf = Math.abs(scroll_x) < (cursorWidth / 2); if (scroll_x < 0) { if (isHalf) { leftX = (mSelectedTab) * cursorWidth + scroll_x * 2 + mItemLeft; rightX = (mSelectedTab) * cursorWidth + mItemRight; } else { leftX = (mSelectedTab - 1) * cursorWidth + mItemLeft; rightX = (mSelectedTab) * cursorWidth + mItemRight + (scroll_x + (cursorWidth / 2)) * 2; } } else if (scroll_x > 0) { if (isHalf) { leftX = mSelectedTab * cursorWidth + mItemLeft; rightX = (mSelectedTab) * cursorWidth + mItemRight + scroll_x * 2; } else { leftX = mSelectedTab * cursorWidth + mItemLeft + (scroll_x - (cursorWidth / 2)) * 2; rightX = (mSelectedTab + 1) * cursorWidth + mItemRight; } } else { leftX = mSelectedTab * cursorWidth + mItemLeft; rightX = mSelectedTab * cursorWidth + mItemRight; } }接下来便就是根据线条的最左边和最右边距离的点便可以在View上面绘制出线条
float bottomY = getHeight(); float topY = bottomY - mFooterLineHeight; drawLineRect.left = leftX; drawLineRect.right = rightX; drawLineRect.bottom = bottomY; drawLineRect.top = topY; int roundXY = isRoundRectangleLine ? (mFooterLineHeight / 2) : 0; canvas.drawRoundRect(drawLineRect, roundXY, roundXY, mPaintFooterLine);新闻热点
疑难解答