I am new to Android development and at the moment I must make a decision of where to control the gesture input, but I just don’t know the pros and cons of where to grab the touch input. I have been given two alternatives, can you please explain to me the pros and cons of either way?
Set listener on View; implement methods:
faceView.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View arg0, MotionEvent arg1){
return false;
}
);
or
Override method within View
public boolean onTouchEvent(MotionEvent event){
return false;
}
APPROACH 1: Anonymous Inner Type.
This is Anonymous, because it is a declaration without a name. There is no
OnTouchListener mytouch =, there is only the declarationnew OnTouchListener(). This is inner, because it is inside another class, and it is a type because it is an implementation of an interface.OK, so with that in mind. This approach is more convenient for developers. Functionality is isolated (generally by the declaration of the listenerable) and this is easily managed. But this convenience comes with a cost. Assume you have buttons, with ten onClickListeners. With this approach, the garbage collection queue will fill up faster with each new anonymous inner type.
But does it matter? Not really. If you are trying to get every microsecond of performance out of your system, then sure don’t use this approach. But generally, this is viable.
APPROACH 2: Single Inheritance
Assuming you read the above, this approach has a much lower cost for creation and cleanup. There is only 1 extra class instantiated, and only 1 object added to the GC queue.
This is the approach I use, and have used for a while. It’s also what I see in Google’s sample source code.
But it’s not perfect! The implementation of
onTouchEventwill end up looking as such:SO
Honestly, it doesn’t matter. If you want the highest performance possible, use a static onTouchEvent listener, and you won’t have to pay the above mentioned costs, but for the most part they are not that expensive anyways.