效果图
代码
public class CustomScrollView extends ViewGroup {
private final int mMScreenHeight;
private Scroller mScroller;
private int mLastY;
private int mStart;
private int mEnd;
public CustomScrollView (Context context, AttributeSet attrs) {
super (context, attrs);
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
mMScreenHeight = metrics.heightPixels;
mScroller = new Scroller(context);
}
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super .onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
for (int i = 0 ; i < childCount; i++) {
View childView = getChildAt(i);
measureChild(childView,widthMeasureSpec,heightMeasureSpec);
}
}
@Override
protected void onLayout (boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
MarginLayoutParams params = (MarginLayoutParams) getLayoutParams();
params.height = childCount*mMScreenHeight;
for (int i = 0 ; i < childCount; i++) {
View childView = getChildAt(i);
childView.layout(0 ,i*mMScreenHeight,r,(i+1 )*mMScreenHeight);
}
}
@Override
public boolean onTouchEvent (MotionEvent event) {
int y = (int ) event.getY();
int action = event.getAction();
switch (action){
case MotionEvent.ACTION_DOWN:
mLastY = y;
mStart = getScrollY();
break ;
case MotionEvent.ACTION_MOVE:
if (!mScroller.isFinished()){
mScroller.abortAnimation();
}
int dy = mLastY - y;
if (getScrollY()<0 ){
dy =0 ;
}
if (getScrollY()>getHeight() - mMScreenHeight){
dy = 0 ;
}
scrollBy(0 ,dy);
mLastY = y;
break ;
case MotionEvent.ACTION_UP:
mEnd = getScrollY();
int dScrollY = mEnd - mStart;
if (dScrollY>0 ){
if (dScrollY > mMScreenHeight/3 ){
mScroller.startScroll(0 ,getScrollY(),0 ,mMScreenHeight - dScrollY);
}else {
mScroller.startScroll(0 ,getScrollY(),0 ,-dScrollY);
}
}else {
if (-dScrollY>mMScreenHeight/3 ){
mScroller.startScroll(0 ,getScrollY(),0 ,-mMScreenHeight - dScrollY);
}else {
mScroller.startScroll(0 ,getScrollY(),0 ,-dScrollY);
}
}
invalidate();
break ;
}
return true ;
}
@Override
public void computeScroll () {
super .computeScroll();
if (mScroller.computeScrollOffset()){
scrollTo(0 ,mScroller.getCurrY());
postInvalidate();
}
}
}