Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A View's onTouchListener vs onTouchEvent

What is the difference between a view's onTouchEvent :

public class MyCustomView extends View {
    // THIS :
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }
}

and its onTouchListener :

MyCustomView myView = (MyCustomView) findViewById(R.id.customview);
myView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public void onClick(View arg0) {
        // do something
    }
});

or

public class MyCustomView extends View {

    public MyCustomView(Context context, AttributeSet attrs) {
        // THIS :
        setOnTouchListener(new View.OnTouchListener() {
            @Override
            public void onClick(View arg0) {
                // do something
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }
}

If this two is different,
Do we need to implement both ?
Which one is invoked first ?

If I have some scrolling and zooming functionality, should I implement them inside onTouchEvent or onTouchListener ?

like image 938
topher Avatar asked Oct 27 '13 16:10

topher


People also ask

What is onTouchEvent?

onTouchEvent is a method implemented by the View, Activity and other base classes like LinearLayout, etc.. public boolean onTouchEvent(MotionEvent event) { throw new RuntimeException("Stub!" ); } you can override this method by any derived classes.

What is OnTouchListener in Android?

Added in API level 1. public abstract boolean onTouch (View v, MotionEvent event) Called when a touch event is dispatched to a view. This allows listeners to get a chance to respond before the target view.

How do you use onTouchEvent?

After the Math. abs() calls, you're essentially testing if their finger is farther down the screen than it is across the screen. Store the initial down coordinates as member variables and set them during ACTION_DOWN . You declared two floats (touchX and touchY) inside the onTouchEvent method.


1 Answers

Answer by LeeYiHong is correct, and the other very important thing is what is written at http://developer.android.com/reference/android/view/View.OnTouchListener.html:

The callback [i.e. View.OnTouchListener -> onTouch(View v, MotionEvent event)] will be invoked before the touch event [i.e. onTouchEvent(MotionEvent)] is given to the view.

like image 160
Elia12345 Avatar answered Oct 10 '22 08:10

Elia12345