<span style="font-family:Comic Sans MS;font-size:14px;">public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
// float x = event.getRawX();
// float y = event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastX = x;
mLastY = y;
break;
case MotionEvent.ACTION_MOVE:
int offsetX = (int) (x - mLastX);
int offsetY = (int) (y - mLastY);
<span style="color:#ff0000;">// 使用layout进行位移</span>
// layout(getLeft() + offsetX, getTop() + offsetY, getRight()
// + offsetX, getBottom() + offsetY);
<span style="color:#ff0000;">// 使用offsetLeftAndRight、offsetTopAndBottom</span>
// offsetLeftAndRight(offsetX);
// offsetTopAndBottom(offsetY);
<span style="color:#ff0000;">// 使用MarginLayoutParams</span>
// marginLayoutParams = (MarginLayoutParams) getLayoutParams();
// marginLayoutParams.setMargins(getLeft() + offsetX, getTop()
// + offsetY, 0, 0);
// setLayoutParams(marginLayoutParams);
<span style="color:#cc0000;">// 使用scroll,参数为正向上滑</span>
((View) getParent()).scrollBy(-offsetX, -offsetY);
// 使用绝对坐标一定要重新设置初始坐标
// mLastX = x;
// mLastY = y;
break;
case MotionEvent.ACTION_UP:
<span style="color:#ff0000;">// 使用scroller</span>
View viewParent = ((View) getParent());
//不知道为什么滑出屏幕后不会滑回来
mScroller.startScroll(viewParent.getScrollX(),
viewParent.getScrollY(), -viewParent.getScrollX(),
-viewParent.getScrollY());
viewParent.invalidate();
break;
}
return true;
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
((View) getParent()).scrollTo(mScroller.getCurrX(),
mScroller.getCurrY());
invalidate();
}
}</span>
实现滑动的几种简单方法
最新推荐文章于 2021-06-25 05:50:24 发布