CustomView overriding onTouch() and setting additional GestureDetector via setOnTouchListener()

593 views Asked by At

Is it possible to create custom view that both overrides function onTouch() inside this custom view implementation, and enables to set custom GestureDetector via setOnTouchListener().

  1. I would like to Override onTouch() method to implement some drawing logic in the View related to touch gestures.
  2. Than I would like to use such self-contained custom view to attach to it GestureDetector to detect and handle some custom gestures on this view inside Activity.

It works for me only if I have onTouch() drawing implementation, or only setOnTouchListener() to detect gestures. Maybe I could place this gesture detection inside view. But I would prefer to have this as separate loosely coupled reusable component rather than tightly coupled gesture detector.

1

There are 1 answers

2
Anton Potapov On BEST ANSWER

You can do somethink like this:

public class CustomTouchView extends View {

    private OnTouchListener onTouchListener;

    public CustomTouchView(Context context) {
        super(context);
    }

    @Override
    public void setOnTouchListener(OnTouchListener l) {
        super.setOnTouchListener(l);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (onTouchListener != null) {
            return onTouchListener.onTouch(this, event);
        } else {
            return super.onTouchEvent(event);
        }

        // or implement your custom touch logic here 
    }
}