开发者

Understanding setOnClickListener, View.OnClickListener(), onClick(View v) as it relates to the Model-View-Controller concept

开发者 https://www.devze.com 2023-03-13 12:18 出处:网络
I\'m clear on how the id of my xml button gets cast as a Button and ultimately to the sayIt field, however...

I'm clear on how the id of my xml button gets cast as a Button and ultimately to the sayIt field, however...

Button sayIt = (Button) findViewById(R.id.sayit);

...is it setOnClickListener that "registers" with the Controller to be notified when the button is clicked? If so, then is View.OnClickListener() and its onClick(View v) method where Controller first tells my code, hey I've been clicked and this is what gets kicked up the food chain?

sayIt.setOnClickListener(new View.OnClickListener() {
@Override
public vo开发者_JAVA百科id onClick(View v) {

    // Does something cool

}
});


For most use cases, yes, View.OnClickListener#onClick() is the standard "do something when this thing is clicked" idiom. I say most, because the actual underlying implementation is a bit more involved than that, and there are different ways in which the touch event travels up the view hierarchy, before being detected as a "click" event, and propagating back down the hierarchy as a click event -- but unless you're implementing custom views, and need to do custom touch-based tracking, you generally don't need to worry about those events.

For example, if you set a View.OnTouchListener on the view, you get every touch event (down, motion, up, and in supported devices, even multiple pointers). In the onTouchEvent() handler, if you return true, it tells the view "I was interested in this motion event, and I have consumed the event; therefore pretend that the event never happened and stop propagating/processing it" -- by doing that, you would actually interfere with the standard OnClickListener click event detection.

But in most cases, if you want something to happen because you clicked on a Button (surprise, surprise :), View.OnClickListener and View#setOnClickListener() are what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消