安卓左右滑动事件监听
importandroid.os.Bundle;importandroid.app.Activity;importandroid.content.Context;importandroid.util.Log;importandroid.widget.RelativeLayout;publicclassMainActivityextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//这里的xml是一个空白的layout//需要监听左右滑动事件的viewRelativeLayoutview=(RelativeLayout)this.findViewById(R.id.layout);//setLongClickable是必须的view.setLongClickable(true);view.setOnTouchListener(newMyGestureListener(this));}/***继承GestureListener,重写left和right方法*/privateclassMyGestureListenerextendsGestureListener{publicMyGestureListener(Contextcontext){super(context);}@Overridepublicbooleanleft(){Log.e("test","向左滑");returnsuper.left();}@Overridepublicbooleanright(){Log.e("test","向右滑");returnsuper.right();}}}importandroid.content.Context;importandroid.view.GestureDetector.SimpleOnGestureListener;importandroid.view.GestureDetector;importandroid.view.View;importandroid.view.View.OnTouchListener;importandroid.view.MotionEvent;/***实现监听左右滑动的事件,哪个view需要的时候直接setOnTouchListener就可以用了*@authorLinZhiquan**/publicclassGestureListenerextendsSimpleOnGestureListenerimplementsOnTouchListener{/**左右滑动的最短距离*/privateintdistance=100;/**左右滑动的最大速度*/privateintvelocity=200;privateGestureDetectorgestureDetector;publicGestureListener(Contextcontext){super();gestureDetector=newGestureDetector(context,this);}/***向左滑的时候调用的方法,子类应该重写*@return*/publicbooleanleft(){returnfalse;}/***向右滑的时候调用的方法,子类应该重写*@return*/publicbooleanright(){returnfalse;}@OverridepublicbooleanonFling(MotionEvente1,MotionEvente2,floatvelocityX,floatvelocityY){//TODOAuto-generatedmethodstub//e1:第1个ACTION_DOWNMotionEvent//e2:最后一个ACTION_MOVEMotionEvent//velocityX:X轴上的移动速度(像素/秒)//velocityY:Y轴上的移动速度(像素/秒)//向左滑if(e1.getX()-e2.getX()>distance&&Math.abs(velocityX)>velocity){left();}//向右滑if(e2.getX()-e1.getX()>distance&&Math.abs(velocityX)>velocity){right();}returnfalse;}@OverridepublicbooleanonTouch(Viewv,MotionEventevent){//TODOAuto-generatedmethodstubgestureDetector.onTouchEvent(event);returnfalse;}publicintgetDistance(){returndistance;}publicvoidsetDistance(intdistance){this.distance=distance;}publicintgetVelocity(){returnvelocity;}publicvoidsetVelocity(intvelocity){this.velocity=velocity;}publicGestureDetectorgetGestureDetector(){returngestureDetector;}publicvoidsetGestureDetector(GestureDetectorgestureDetector){this.gestureDetector=gestureDetector;}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。