安卓左右滑动事件监听
import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.util.Log; import android.widget.RelativeLayout; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);//这里的xml是一个空白的layout //需要监听左右滑动事件的view RelativeLayout view = (RelativeLayout) this.findViewById(R.id.layout); //setLongClickable是必须的 view.setLongClickable(true); view.setOnTouchListener(new MyGestureListener(this)); } /** * 继承GestureListener,重写left和right方法 */ private class MyGestureListener extends GestureListener { public MyGestureListener(Context context) { super(context); } @Override public boolean left() { Log.e("test", "向左滑"); return super.left(); } @Override public boolean right() { Log.e("test", "向右滑"); return super.right(); } } } import android.content.Context; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.GestureDetector; import android.view.View; import android.view.View.OnTouchListener; import android.view.MotionEvent; /** * 实现监听左右滑动的事件,哪个view需要的时候直接setOnTouchListener就可以用了 * @author LinZhiquan * */ public class GestureListener extends SimpleOnGestureListener implements OnTouchListener { /** 左右滑动的最短距离 */ private int distance = 100; /** 左右滑动的最大速度 */ private int velocity = 200; private GestureDetector gestureDetector; public GestureListener(Context context) { super(); gestureDetector = new GestureDetector(context, this); } /** * 向左滑的时候调用的方法,子类应该重写 * @return */ public boolean left() { return false; } /** * 向右滑的时候调用的方法,子类应该重写 * @return */ public boolean right() { return false; } @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轴上的移动速度(像素/秒) // 向左滑 if (e1.getX() - e2.getX() > distance && Math.abs(velocityX) > velocity) { left(); } // 向右滑 if (e2.getX() - e1.getX() > distance && Math.abs(velocityX) > velocity) { right(); } return false; } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub gestureDetector.onTouchEvent(event); return false; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } public int getVelocity() { return velocity; } public void setVelocity(int velocity) { this.velocity = velocity; } public GestureDetector getGestureDetector() { return gestureDetector; } public void setGestureDetector(GestureDetector gestureDetector) { this.gestureDetector = gestureDetector; } }
当前文章:安卓左右滑动事件监听
分享链接:http://azwzsj.com/article/pjpooc.html