標籤:android style blog http io ar os 使用 sp
ViewDragHelper是用來移動ViewGroup中子View的,之前寫View的移動都是通過scrollTo來實現,但是它移動的是VIew中的內容,ViewGroup中的所有的子View都會移動,我一直在找能夠移動子View的方法。在Google的IO大會上,發布的DrawerLayout和SlidingPaneLayout,其內部實現都是使用的ViewDragHelper實現的。 首先使用方法:1.ViewDragHelper不能被new出來,是通過 private void init(Context context){ mDragHelper = ViewDragHelper.create(this, 0.2f, new DragHelperCallback());
}
建立出來的。 2.在ViewGroup中的打斷觸摸事件的方法中:由ViewDragHelper自己來判斷是否去打斷觸摸事件。 @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) { mDragHelper.cancel(); return false; } return mDragHelper.shouldInterceptTouchEvent(ev); }
3. 在ViewGroup的觸摸事件中: @Override public boolean onTouchEvent(MotionEvent ev) { mDragHelper.processTouchEvent(ev); return true; }4.整個手勢的識別通過ViewDragHelper自己完成,然後自己回調自己的介面,通過介面來完成相應的動作:class DragHelperCallback extends Callback{ @Override public boolean tryCaptureView(View arg0, int arg1) { System.out.println("positionID=="+arg1); return arg0 == getTopView(); } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { final int leftBound = getPaddingLeft(); final int rightBound = getWidth() - getTopView().getWidth(); final int newLeft = Math.min(Math.max(left, leftBound), rightBound); return newLeft; } @Override public int clampViewPositionVertical(View child, int top, int dy) { final int topBound = getPaddingTop(); final int bottomBound = getHeight() - getTopView().getHeight(); final int newTop = Math.min(Math.max(top, topBound), bottomBound); return newTop; } } private View getTopView(){ return getChildAt(1); } private View getBottomView(){ return getChildAt(0); } 這裡處理的是左右滑動的事件。 簡單的使用就是這樣的。先上一下Demo的:
ViewDragHelper封裝了手勢,大大的簡化了很多的手勢處理。我參照別人的部落格和Demo,自己實現了相同的效果,在下一篇部落格中,放出源碼。邊學邊練。 我的github地址:https://github.com/flyme2012我的部落格地址:http://www.cnblogs.com/flyme2012/
android 學習之ViewDragHelper