无限滑动切换View


import android.content.Context;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

public class SView extends View {
protected Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
private Scroller mScroller;
private int index;//坐标
private int criticalWidth;//
private int width, height;
private int lastPointX, lastPointY;
private int lastMoveX, lastMoveY;
private boolean isEvent;

public SView(Context context) {
this(context, null);
}

public SView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public SView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mScroller = new Scroller(context);
mPaint.setTextAlign(Paint.Align.CENTER);
}

@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
invalidate();
} else {
requestLayout();
}
}

@Override

public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mScroller.forceFinished(true);
isEvent = false;
lastPointX = (int) event.getX();
lastPointY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
if (Math.abs(lastPointX - event.getX()) > 100) {
isEvent = true;
}
if (isEvent) {
int totalMoveX = (int) (lastPointX - event.getX()) + lastMoveX;
smoothScrollTo(totalMoveX);
}
break;
case MotionEvent.ACTION_UP:
if (isEvent) {
if (Math.abs(lastPointX - event.getX()) > 25) {
if (lastPointX > event.getX() &&
Math.abs(lastPointX - event.getX()) >= criticalWidth) {
index++;
} else if (lastPointX < event.getX() &&
Math.abs(lastPointX - event.getX()) >= criticalWidth) {
index--;
}
smoothScrollTo(width * index);
lastMoveX = width * index;
}
}
break;
}
return true;
}

@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
width = w;
height = h;
criticalWidth = (int) (1F / 5F * width);
}

@Override
protected void onDraw(Canvas canvas) {
//根据坐标画左右和中间的视图
draw(canvas, width * (index - 1));
draw(canvas, width * index);
draw(canvas, width * (index + 1));
}

private void draw(Canvas canvas, int x) {
canvas.save();
canvas.translate(x, 0);
canvas.drawCircle(width / 2, height / 2, 20, mPaint);
canvas.restore();
}

private void smoothScrollTo(int fx) {
int dx = fx - mScroller.getFinalX();
int dy = -mScroller.getFinalY();
smoothScrollBy(dx, dy);
}

private void smoothScrollBy(int dx, int dy) {
mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx, dy, 500);
invalidate();
}
}

你可能感兴趣的:(无限滑动切换View)