Scroller 实现的弹性回弹的LinearLayout
由于公司业务发展,多app需求很少,被调到java后台开发接口三个月了,还要我继续做 java,最近有点想换工作,不得不重新看看基础知识了。
晚上看到了滑动的实现方式,平滑滑package com.example.alter.scrollers.scroller;
import android.content.Context; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.widget.LinearLayout; import android.widget.Scroller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by alter on 16/4/18. */ public class ScrollLinearLayout extends LinearLayout { Logger logger = LoggerFactory.getLogger(ScrollLinearLayout.class); private Scroller mScroller; private GestureDetector gestureDerector; public ScrollLinearLayout(Context context) { super(context, null); } public ScrollLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); mScroller = new Scroller(context); gestureDerector = new GestureDetector(context, new GestureDetector.OnGestureListener() { @Override public boolean onDown(MotionEvent e) { return true; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { int disY = (int) ((distanceY-0.5)/2); beginScroll(0,disY); return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } }); } private void beginScroll(int dx, int dy) { mScroller.startScroll(mScroller.getFinalX(),mScroller.getFinalY(),dx,dy); invalidate(); System.out.println("smoothScrollBy()---> " + "mScroller.getFinalX()="+mScroller.getFinalX()+","+ "mScroller.getFinalY()="+mScroller.getFinalY()); } private void prepareScroll(int fx, int fy) { int dx=fx-mScroller.getFinalX(); int dy=fy-mScroller.getFinalY(); beginScroll(dx,dy); } @Override public boolean onTouchEvent(MotionEvent event) {switch (event.getAction()){ case MotionEvent.ACTION_UP: prepareScroll(0,0); break; default: return gestureDerector.onTouchEvent(event); } return super.onTouchEvent(event); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { logger.info("CurX" + mScroller.getCurrX() + "CurY" + mScroller.getCurrY()); scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); postInvalidate(); } super.computeScroll(); } }
只实现了垂直方向的回弹效果。
滑动时,调用手势监听器的滑动;
手指抬起,调用Scroller滑动到0,0位置,完成回弹效果。