在前面,已经制作了 标签页和viewpager同步变化效果,但是有个细节写的不够好,就是上面标签尽量居中的时候,下面viewpager和上面标签页同步选取到合适标签后才进行居中,这样的做法体验不够好,所以,接着写个同步滚动。
同步滚动的关键是每个时刻都要滚动,就是当viewpager调用时onPageScrolled,除了更新指示器位置,同步也要更新滚动条位置,这里将onPageScrolled中调用的followPos()方法,重新展示,下面会做说明。
public void followPos(int position, float positionOffset) {
followPos = position;
if(fromTab){
int moved = 0;
if(selectedPos!=container.getChildCount()-1){
int leftNext = container.getChildAt(selectedPos+1).getLeft();
int leftNow = container.getChildAt(selectedPos).getLeft();
moved = (int) ((leftNext - leftNow)*positionOffset);
}else{
int leftNow = container.getChildAt(selectedPos).getLeft();
int leftLast = container.getChildAt(selectedPos-1).getLeft();
moved = (int) ((leftNow - leftLast)*positionOffset);
}
int newLeft = container.getChildAt(newPos).getLeft();
int oldLeft = container.getChildAt(selectedPos).getLeft();
int posLeft = container.getChildAt(position).getLeft();
int moveDistance = posLeft - oldLeft + moved;
int allDistance = newLeft-oldLeft;
if(allDistance == 0){
followOffset = 0;
}else
followOffset = moveDistance*1.0f / allDistance;
if(followOffset == 1) {
followOffset = 0;
selectedPos = newPos;
}
int realLeft = posLeft + moved;
int realWidth = container.getChildAt(selectedPos).getWidth();
int scrollPos = (int) (realLeft - (getWidth() - realWidth) / 2);
scrollTo(scrollPos, 0);
}else{
if(positionOffset != 0)
newPos = followPos + 1;
else
newPos = followPos;
followOffset = positionOffset;
int posLeft = container.getChildAt(position).getLeft();
int moved = (int) (container.getChildAt(position).getWidth() * followOffset);
int realLeft = posLeft + moved;
int realWidth = container.getChildAt(selectedPos).getWidth();
int scrollPos = (int) (realLeft - (getWidth() - realWidth) / 2);
scrollTo(scrollPos, 0);
}
invalidate();
}
主要是fromTab的:
int realLeft = posLeft + moved;
int realWidth = container.getChildAt(selectedPos).getWidth();
int scrollPos = (int) (realLeft - (getWidth() - realWidth) / 2);
scrollTo(scrollPos, 0);
和else里面的:
int posLeft = container.getChildAt(position).getLeft();
int moved = (int) (container.getChildAt(position).getWidth() * followOffset);
int realLeft = posLeft + moved;
int realWidth = container.getChildAt(selectedPos).getWidth();
int scrollPos = (int) (realLeft - (getWidth() - realWidth) / 2);
scrollTo(scrollPos, 0);
简单的说就是滚动方式和之前的方式相同,但是realLeft值要加上一个移动的偏移量,另外注意这里用的是scrollTo而不是smoothScrollTo,smothScrollTo有中断之前滚动的特性,如果在移动过程中使用,是看不出效果的。所以此处要使用scrollTo。
模仿项目地址:https://github.com/nfwuzhongdemeng/ImitateNBA
原项目地址:https://github.com/smuyyh/SprintNBA