在项目中用到PagerSlidingTabStrip,但是下面的滑块有点丑,所以再原来的代码上进行了一定的修改,将固定的几个title下面的滑块定义成与文字长度相同 并调节相应长度
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode() || tabCount == 0) {
return;
}
final int height = getHeight();
// draw indicator line
rectPaint.setColor(indicatorColor);
// default: line below current tab
View currentTab = tabsContainer.getChildAt(currentPosition);
float lineLeft = 0.0f;
float lineRight = 0.0f;
int parentWidth;
int sonWidth = 0;
int misTakeWidth = 0;
if(!(currentTab instanceof RelativeLayout)){
lineRight = currentTab.getRight();
lineLeft = currentTab.getLeft();
}else{
parentWidth = currentTab.getWidth();
sonWidth = ((RelativeLayout) currentTab).getChildAt(0).getWidth();
misTakeWidth = (parentWidth - sonWidth)/2;
lineLeft = currentTab.getLeft() + misTakeWidth;
lineRight = lineLeft + sonWidth;
// lineRight = currentTab.getRight() - misTakeWidth;
}
// if there is an offset, start interpolating left and right coordinates between current and next tab
if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {
View nextTab = tabsContainer.getChildAt(currentPosition + 1);
if((nextTab instanceof RelativeLayout)){
final float nextTabLeft = nextTab.getLeft()+misTakeWidth;
final float nextTabRight = nextTabLeft + sonWidth;
lineLeft = ((currentPositionOffset)* nextTabLeft + (1f - (currentPositionOffset)) * lineLeft);
lineRight = lineLeft + sonWidth;
}else{
final float nextTabLeft = nextTab.getLeft();
final float nextTabRight = nextTab.getRight();
lineLeft = ((currentPositionOffset) * nextTabLeft + (1f - (currentPositionOffset)) * lineLeft);
lineRight = ((currentPositionOffset) * nextTabRight + (1f - (currentPositionOffset)) * lineRight);
}
}
canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height-20, rectPaint);
// draw underline
// rectPaint.setColor(getResources().getColor(R.color.appmain));
rectPaint.setColor(underlineColor);
canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);
// draw divider
dividerPaint.setColor(dividerColor);
for (int i = 0; i < tabCount - 1; i++) {
View tab = tabsContainer.getChildAt(i);
if(tab instanceof RelativeLayout){
// tab = ((RelativeLayout) tab).getChildAt(0);
canvas.drawLine(((RelativeLayout) tab).getChildAt(0).getRight(), dividerPadding, ((RelativeLayout) tab).getChildAt(0).getRight(), height - dividerPadding, dividerPaint);
// canvas.drawLine(tab.getRight() + ((RelativeLayout) tab).getChildAt(0).getRight(), dividerPadding, tab.getRight() + ((RelativeLayout) tab).getChildAt(0).getRight(), height - dividerPadding, dividerPaint);
}else{
canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint);
}
}
}
主要的改变就是在onDraw()方法里面,因为我把滑块定义成一个子View外面又嵌套一个父控件,所以麻烦点儿的地方就是计算子view的坐标和移动时的坐标