Difference between OnClick() event and OnClickListener?

后端 未结 16 2429
醉话见心
醉话见心 2020-12-01 12:13

I\'m always using onclick() event in most of my projects. But, I read about OnClickListener(). Can anyone tell what\'s the difference between these

16条回答
  •  执念已碎
    2020-12-01 12:51

    I am assuming by onClick that you use is the one that you defines in XML Layout. These two are alternative that serve same function but implemented differently.

    1. The onClick with function binding in XML Layout is a binding between onClick and the function that it will call. The function have to have one argument (the View) in order for onClick to function.

    2. An OnClickListener is an interface that any class could implement. Since it is an interface that any class could implement, this has more flexibility and more complex in its form. Few flexibilities that you could have with OnClickListener

      • You could easily swap one listener implementation with another if you need to.
      • An OnClickListener enable you to separate the action/behavior of the click event from the View that triggers the event. While for simple cases this is not such a big deal, for complex event handling, this could mean better readability and maintainability of the code
      • Since OnClickListener is an interface, the class that implements it has flexibilities in determining the instance variables and methods that it needs in order to handle the event. Again, this is not a big deal in simple cases, but for complex cases, we don't want to necessary mix up the variables/methods that related to event handling with the code of the View that triggers the event.

提交回复
热议问题