android-使用Scroller進行y軸上的平移
阿新 • • 發佈:2018-12-09
scroller平移是指利用scroller進行計算,用scrollTo進行實際的的平移,移動的是內容,即子view相對於父view的位置,而非位置。
1.scrollTo和scrollBy
scrollTo(int x, int y),相對於初始位置進行平移。
scrollBy(int x, int y),呼叫scrollTo方法進行平移,相對於上一次平移的位置進行平移。
2.scroller
對平移進行計算,返回平移的位置等。
//初始化Scroller。 Scroller mScroller = new Scroller(getContext()); //呼叫startScroll方法傳入引數進行計算。 mScroller.startScroll(0, startY, 0, dy, duration); //重新整理介面 invalidate();
3.computeScroll
參考Scroller計算出來的值進行進行平移。
@Override
public void computeScroll() {
//計算是否完成滾動
if (mScroller.computeScrollOffset()) {
//實際上急性滾動
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
//重新整理介面
postInvalidate();
}
}
4.全部程式碼
public class TestScrollerView extends RelativeLayout{ private static final String TAG = "TestScrollerView"; private Button child; private Scroller mScroller = new Scroller(getContext()); public TestScrollerView(Context context) { this(context,null); } public TestScrollerView(Context context, AttributeSet attrs) { this(context, attrs,0); } public TestScrollerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); initView(); } private void initView(){ child = (Button) getChildAt(0); child.setOnTouchListener(mOnTouchListener); } private float mLastRawY; private int mStartRawY = 0; private OnTouchListener mOnTouchListener = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_DOWN: mLastRawY = event.getRawY(); break; case MotionEvent.ACTION_MOVE: int dy = (int) (mLastRawY - event.getRawY()); smoothScrollBy(mStartRawY, dy,100); mStartRawY = mScroller.getFinalY(); mLastRawY = event.getRawY(); break; case MotionEvent.ACTION_UP: break; default: } return false; } }; public void smoothScrollBy(int startY, int dy,int duration) { mScroller.startScroll(0, startY, 0, dy, duration); invalidate(); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); postInvalidate(); } } }