时间:2021-01-04 16:12:26 | 栏目:Android代码 | 点击:次
最近想实现Android左滑弹出菜单框,右滑消失菜单这个个功能。了解了一下Android 的滑动事件,必须是在view组件或者Activity上实现,同时必须实现OnTouchListener, OnGestureListener这个两个接口。
public class MyRelativeLayout extends RelativeLayout implements GestureDetector.OnGestureListener{ private float mPosX, mPosY, mCurPosX, mCurPosY; private static final int FLING_MIN_DISTANCE = 20;// 移动最小距离 private static final int FLING_MIN_VELOCITY = 200;// 移动最大速度 //构建手势探测器 GestureDetector mygesture = new GestureDetector(this); public MyRelativeLayout(Context context){ super(context) } public MyRelativeLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } public MyRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } @Override public boolean onTouchEvent(MotionEvent arg0) { // TODO Auto-generated method stub return mDetector.onTouchEvent(arg0); } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub // e1:第1个ACTION_DOWN MotionEvent // e2:最后一个ACTION_MOVE MotionEvent // velocityX:X轴上的移动速度(像素/秒) // velocityY:Y轴上的移动速度(像素/秒) // X轴的坐标位移大于FLING_MIN_DISTANCE,且移动速度大于FLING_MIN_VELOCITY个像素/秒 //向左 if (e1.getY() - e2.getY() > FLING_MIN_DISTANCE){ // && Math.abs(velocityX) > FLING_MIN_VELOCITY) { collapse(); } //向上 if (e2.getY() - e1.getY() > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) { } return false; } }