Difference between OnClick() event and OnClickListener?

后端 未结 16 2388
醉话见心
醉话见心 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 13:06

    There are a couple reasons why you might want to programmatically set an OnClickListener. The first is if you ever want to change the behavior of your button while your app is running. You can point your button at another method entirely, or just disable the button by setting an OnClickListener that doesn't do anything.

    When you define a listener using the onClick attribute, the view looks for a method with that name only in its host activity. Programmatically setting an OnClickListener allows you to control a button's behavior from somewhere other than its host activity. This will become very relevant when we talk about Fragments, which are basically mini activities, allowing you to build reusable collections of views with their own lifecycle, which can then be assembled into activities. Fragments always need to use OnClickListeners to control their buttons, since they're not Activities, and won't be searched for listeners defined in onClick.

提交回复
热议问题