本文讲述了Android中View跟随手指滑动效果的实例代码。分享给大家供大家参考,具体如下:
1、android View 主要6种滑动方法,分别是
2、实现效果图
3、自定义中使用layout()方法实习view的滑动
public class MoveView extends View { private int lastX, lastY; public MoveView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public MoveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public MoveView(Context context) { super(context); } public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: int offsetX = x - lastX;//计算滑动的距离 int offsetY = y - lastY; //重新放置新的位置 layout(getLeft() + offsetX, getTop() + offsetY, getRight() + offsetX, getBottom() + offsetY); } return true; } }
2、offsetLeftAndRight()和offsetTopAndBottom()
public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: int offsetX = x - lastX;//计算滑动的距离 int offsetY = y - lastY; //重新放置新的位置 // layout(getLeft() + offsetX, getTop() + offsetY, getRight() + offsetX, getBottom() + offsetY); offsetLeftAndRight(offsetX); offsetTopAndBottom(offsetY); } return true; }
3、LayoutParams 改变布局参数的方法:
public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: int offsetX = x - lastX;//计算滑动的距离 int offsetY = y - lastY; //重新放置新的位置 // layout(getLeft() + offsetX, getTop() + offsetY, getRight() + offsetX, getBottom() + offsetY); // offsetLeftAndRight(offsetX); // offsetTopAndBottom(offsetY); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams(); layoutParams.leftMargin = getLeft()+offsetX; layoutParams.topMargin = getTop() +offsetY; setLayoutParams(layoutParams); } return true; }
4、当然使用动画 ,scrollBy()和 scrollTo()也可以使view滑动,不足的是使用scrollBy()和 scrollTo()滑动时,是瞬间完成的,用户体验不太好。
5、Scroller和 View的computeScroll() 结合使用,实现view平滑的移动
public class MoveView extends View { private Scroller mScroller; public MoveView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); mScroller = new Scroller(context); } public MoveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public MoveView(Context context) { super(context); } //重写computeScroll方法 @Override public void computeScroll() { //view在onDraw的时候会调用此方法 super.computeScroll(); if (mScroller.computeScrollOffset()) { ((View) getParent()).scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); invalidate(); } } //在外部调用这个方法即可 public void smoothScrollTo(int destX, int destY) { int scrollX = getScrollX(); int delta = destX - scrollX; mScroller.startScroll(scrollX, 0, delta,0 ,6000); invalidate(); } }