由Activity Do OnBackPress滑动

时间:2015-09-25 18:44:14

标签: android android-activity swipe

它可以将左侧滑动操作捕获到右侧并通过活动运行命令? 在活动的情况下,将识别滑动(从左到右)并运行命令onBackPress(); 我需要在视图中识别滑动并在活动中保留其他组件,并且不知道如何识别该操作是活动还是组件。

1 个答案:

答案 0 :(得分:0)

使用以下代码,它可以有一个响应后退手势的侦听器。使用View setOnTouchListener可以识别移动并执行操作。

执行

        android.view.GestureDetector gestureDetector = new android.view.GestureDetector(this, new GestureDetector(Activity.this));
        View.OnTouchListener gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        };

        view.setOnTouchListener(gestureListener);

GestureDetector.java

public class GestureDetector extends android.view.GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private final Activity activity;

    public GestureDetector(Activity activity){
        this.activity = activity;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                activity.onBackPressed();
            }
        } catch (Exception e) {
            // nothing
        }
        return false;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }
}