最近学习了怎么自己画Viewpager指示器的形状。
新创建一个ViewPagerIndicator类 继承自LinearLayout
- 初始化Paint实例
在它的含有两个参数的构造方法内初始化要画的图形所需要的工具,例如:我们要画一个三角形。首先我们要有一个paint类实例上代码:
public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
//@ parseColor
// * Parse the color string, and return the corresponding color-int.
mPaint.setColor(Color.parseColor("#FFFFFFFF"));
mPaint.setStyle(Paint.Style.FILL);
mPaint.setPathEffect(new CornerPathEffect(3));
覆写onSizeChanged(int w, int h, int oldw, int oldh)这个方法会在View 的大小发生变化的时候调用,所以在这里设置三角形的长和宽并且初始化三角形。
mTriangleWidth = (int) (w / mTabVisibleCount * RADIO_TRIANGLE); mTriangleHeight = mTriangleWidth / 2; mInitTanslateX = w / 2 / mTabVisibleCount - mTriangleWidth / 2; initTriangle();
画三角形的时候要用到path
mPath = new Path();
//@param x The x-coordinate of the start of a new contou(新轮廓)
mPath.moveTo(0, 0);
mPath.lineTo(mTriangleWidth, 0);
mPath.lineTo(mTriangleWidth / 2, -mTriangleHeight);
mPath.close();
-覆写ondispatch方法。在这个方法里绘制三角形
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
//画笔的起点位置
canvas.translate(mInitTanslateX + mTranslateX, getHeight());
canvas.drawPath(mPath, mPaint);
canvas.restore();
super.dispatchDraw(canvas);
Log.d(TAG, "dispatchDraw: ");
}
这样三角形的画出来了,但是现在这个三角形还不可以跟随页面滑动而动。
2.实现指示器跟随手指联动
需要addOnPageChangeListener,内部new 一个ViewPager.OnPageChangeListener(),在它的onpageScrolled这个回调方法里写怎么跟随手指移动的方法,如下:
int tabWidth = getWidth() / mTabVisibleCount;
mTranslateX = (int) (tabWidth * (position + positionOffset));
//tabwidth 跟着一起联动
if (position >=mTabVisibleCount - 2 && positionOffset > 0 &&
getChildCount() > mTabVisibleCount) {
if (mTabVisibleCount != 1) {
//隐藏的position
int hidTabCount = position - (mTabVisibleCount - 2);
this.scrollTo(
(hidTabCount * tabWidth + (int) (tabWidth * positionOffset)), 0);
} else {
this.scrollTo((position * tabWidth + (int) (tabWidth * positionOffset)), 0);
}
}
invalidate();
3.实现tab高亮显示和点击事件
首先写好一个设置tab文字高亮的方法,然后将其加到 onPageSelected内,意思是,到当前页被选中时,tab文字变高亮。
点击时间在创建tab的时候调用。这个添加到自动创建tab 的方法内,和加载完xml文件后的方法内(这个在下篇文章中详细讲).
private void highLightTextView(int position){
resetTextViewColor();
View view = getChildAt(position);
if (view instanceof TextView){
((TextView) view).setTextColor(TEXT_COLOR_LIGHT);
}
private void setTabOnclick() {
int size = getChildCount();
for (int i = 0; i < size; i++) {
View view = getChildAt(i);
final int j = i;
if (view instanceof TextView) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mViewPager.setCurrentItem(j);
}
});
}
}
}