Android自定義View的移動
阿新 • • 發佈:2019-02-20
自定義View的移動
方法1:
通過修改View物件的left,top, right, bottom四個屬性來修改座標。layout(getLeft()+offsetX,getTop()+offsetY,getRight()+offsetX,getBottom()+offsetY);
方法2:
offsetLeftAndRight((int) offsetX);
offsetTopAndBottom((int) offsetY);
方法3:
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams(); ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams(); layoutParams.leftMargin= (int) (getLeft()+offsetX); layoutParams.topMargin= (int) (getTop()+offsetY); setLayoutParams(layoutParams);
方法4:
((View)getParent()).scrollBy(-offsetX,-offsetY);
方法5:
使用Scroller類,可以平滑移動。1、初始化Scroller
mScroller = new Scroller(context);
2、重寫computeScroller()方法draw()方法呼叫該方法,該方法手動呼叫invalidate(),重新整理。直到滑動完成,mScroller.computeScrollOffset()返回false。
@Override public void computeScroll() { super.computeScroll(); //滑動完成時,mScroller.computeScrollOffset()返回false if (mScroller.computeScrollOffset()) { ((View) getParent()).scrollTo( mScroller.getCurrX(),//返回mScroller現在該移動的位置 mScroller.getCurrY()); //手動重新整理 invalidate(); } }
3、啟動scroller
手指離開螢幕時,開始啟動滑動過程
startScroll(int startX, int startY, int dx, int dy)
startScroll(int startX, int startY, int dx, int dy, int duration)
引數:起始位置X,起始位置Y,水平偏移,垂直偏移,滑動時間case MotionEvent.ACTION_UP: View viewGroup = ((View) getParent()); mScroller.startScroll( viewGroup.getScrollX(),//獲取整個過程水平方向移動距離 viewGroup.getScrollY(),//獲取整個過程垂直方向移動距離 -viewGroup.getScrollX(),//讓view移動到開始的位置 -viewGroup.getScrollY()); invalidate();//重新整理,用來啟動draw()方法 break;
方法6:
使用ViewDragHelper類來實現滑動。
1.初始化ViewDragHelper
在ViewGround內部,使用工廠進行初始化。
mViewDragHelper=ViewDragHelper.create(this,callback);
引數:監聽的View,回撥Callback
2.攔截事件
事件傳遞給ViewGroundHelper進行處理
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mViewDragHelper.shouldInterceptTouchEvent(ev);//攔截事件
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
mViewDragHelper.processTouchEvent(ev);
return true;//返回true,不用上級處理。
}
3.重寫computeScroll()方法
@Override
public void computeScroll() {
if(mViewDragHelper.continueSettling(true)){
ViewCompat.postInvalidateOnAnimation(this);
}
}
4.處理回撥Callback
private ViewDragHelper.Callback callback = newViewDragHelper.Callback(){
@Override
public boolean tryCaptureView(View child, int pointerId) {
return mMainView==child;//當觸控mMainView時,開始檢測
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
return 0;//返回0,不發生滑動
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
return left;//返回水平移動距離
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
super.onViewReleased(releasedChild, xvel, yvel);
//手指鬆開,移動到相應的位置
if(mMainView.getLeft()<500){
//關閉選單
mViewDragHelper.smoothSlideViewTo(mMainView,0,0);
ViewCompat.postInvalidateOnAnimation(DragViewGround.this);
}else{
//開啟選單
mViewDragHelper.smoothSlideViewTo(mMainView,300,0);
ViewCompat.postInvalidateOnAnimation(DragViewGround.this);
}
}
};