開始以前先看效果 前邊爲網易雲的效果 後邊爲我實現的效果
git
質量有所壓縮,具體可去下載網易雲音樂自行查看效果github
本demo apk文件下載bash
分析完畢,接下來具體實現
app
public class MyInterceptViewPager extends ViewPager {
private boolean isScrollable = true;
public MyInterceptViewPager(Context context) {
super(context);
}
public MyInterceptViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return isScrollable && super.onTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return isScrollable && super.onInterceptTouchEvent(ev);
}
@Override
public void setCurrentItem(int item) {
super.setCurrentItem(item, false);//表示切換的時候,不須要切換時間。
}
@Override
public void setCurrentItem(int item, boolean smoothScroll) {
super.setCurrentItem(item, smoothScroll);
}
}
複製代碼
public class FixedSpeedScroller extends Scroller {
private int mDuration = 1500;
public FixedSpeedScroller(Context context) {
super(context);
}
public FixedSpeedScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}
public void setmDuration(int time) {
mDuration = time;
}
public int getmDuration() {
return mDuration;
}
}
複製代碼
try {
Field field = ViewPager.class.getDeclaredField("mScroller");
field.setAccessible(true);
FixedSpeedScroller scrollerText = new FixedSpeedScroller(this, new AccelerateInterpolator());
field.set(mTextViewPager, scrollerText);
scrollerText.setmDuration(400);
} catch (Exception e) {
}
複製代碼
mTouchLayout.setOnTouchListener(new View.OnTouchListener() {
float startX;
float startY;//沒有用到
float endX;
float endY;//沒有用到
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
break;
case MotionEvent.ACTION_UP:
endX = event.getX();
endY = event.getY();
WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
Point size = new Point();
windowManager.getDefaultDisplay().getSize(size);
int width = size.x;
if (startX - endX >= (width / 8)){// startX - endX 大於0 且大於寬的1/8 能夠日後翻頁
if (pageIndex == 0){
mImageViewPager.setCurrentItem(1);
mTextPager.setCurrentItem(1, true);
}else if (pageIndex == 1){
mImageViewPager.setCurrentItem(2);
mTextPager.setCurrentItem(2, true);
}
}else if (endX - startX >= (width / 8)){ // endX - startX 大於0 且大於寬的1/8 能夠往前翻頁
if (pageIndex == 2){
mImageViewPager.setCurrentItem(1);
mTextPager.setCurrentItem(1, true);
}else if (pageIndex == 1){
mImageViewPager.setCurrentItem(0);
mTextPager.setCurrentItem(0, true);
}
}
break;
}
return true;
}
});
複製代碼