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);
|
新聞熱點
疑難解答