关键词:onPageScrolled的position参数
今天打算使用viewpager和OnPageChangeListener实现一下底部栏滑动时颜色渐变效果,其中一直有无解的困惑,
class MyOnPageChangedListener implements ViewPager.OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { Log.i("onScrolled",position+"<-position,offset->"+positionOffsetPixels); //识别左右滑动 if(lastOffset==-1){ lastOffset=positionOffsetPixels; scrollCounter++; } else if(lastOffset>positionOffsetPixels&&scrollCounter!=0){ direction=DIRECTION_RIGHT; scrollCounter=0; } else if(lastOffset<positionOffsetPixels&&scrollCounter!=0){ direction=DIRECTION_LEFT; scrollCounter=0; } if(direction!=DIRECTION_UNDEFINED){ // 如果向左滑动,则下一个view变化 if(direction==DIRECTION_LEFT){ if(position!=2){ textViews[position+1]. setBackgroundColor(getGradientColor(backgroundColor,nextColor,positionOffset)); textViews[position]. setBackgroundColor(getGradientColor(curColor,backgroundColor,positionOffset)); } } else{ if(position!=0){ textViews[position]. setBackgroundColor(getGradientColor(curColor,backgroundColor,positionOffset)); textViews[position-1]. setBackgroundColor(getGradientColor(backgroundColor,nextColor,positionOffset)); } } } } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { if(state==0){ curColor = nextColor; nextColor = getNextColor(); direction=DIRECTION_UNDEFINED; lastOffset=-1;//初始化 scrollCounter=0; } } }就是滑动的时候有时不是对应的那个底部tab变色,最后在onPageScrolled里面log一下position之后发现在第三页向左滑动返回第二页的时候position的值竟然是1,而不是2。记下来不要再进坑