Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gesture detection on Fragment

I have an Activity which holds a single Fragment:

getFragmentManager().beginTransaction().add(android.R.id.content, fragment1).commit();

My question is, how can i detect gestures? I tried with OnTouchListener, also with onInterceptTouchEvent method. Basically i want to detect swipes. My SwipeGestureDetector looks like this:

public class SwipeGestureDetector extends SimpleOnGestureListener {

    // ...

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

    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 (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                // right to left swipe

            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                // left to right swipe

            }
        } catch (Exception e) {
            // nothing
        }
        return false;
    }
}

Then i register it in my Activity:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // ..

        SwipeGestureDetector swipeDetector = new SwipeGestureDetector();
        final GestureDetector detector = new GestureDetector(this, swipeDetector);
        findViewById(android.R.id.content).setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return detector.onTouchEvent(event);
            }
        });
    }

Unfortunetaly no swipe gesture is detected. How can i achieve this? Please do not suggest to use ViewPager, i cannot use it.

like image 349
WonderCsabo Avatar asked Nov 16 '13 15:11

WonderCsabo


1 Answers

Here is the workaround which i made for this problem.

I had to override dispatchTouchEvent() method in my Activity. This gets called when a touch event occurs to the window.

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    boolean handled = swipeDetector.onTouchEvent(ev);
    if (!handled) {
        return super.dispatchTouchEvent(ev);
    }

    return handled;
}
like image 145
WonderCsabo Avatar answered Oct 17 '22 04:10

WonderCsabo