How to handle a button being clicked in Android?

前端 未结 2 874
无人及你
无人及你 2021-01-12 20:10

In Android there seems to be 3 common ways of handling button clicks, how much difference is there between the methods? And are any of them \'better\' in some way?

T

2条回答
  •  广开言路
    2021-01-12 20:40

    I've really always seen it as preference. I'm not sure there's any performance advantage to either other than the last two methods may be slightly faster since they're not creating objects at runtime.

    The first option isolates the code to the single button so it's very easy to debug since you know only that code will be executed when that button is clicked. However, many buttons can cause initialization methods to expand to large sizes.

    The last two methods put all button handling in one place which can be convenient and cleaner at times, but with many buttons you have to decipher which button was tapped by the user via the v.getId() method.

    The last option allows you to easily specify specific methods for specific buttons so you can separate them out like that, but again you'll have many methods used for single purposes.

    I've always used the inline method (anonymous class) for custom dialog windows that have buttons since it keeps the code with the rest of the dialog rather than in an activity or class. I just initialize the buttons of the custom dialog when I override the onCreateDialog.

    I implement the OnClickListener on the Activity if the buttons are on the main window.

提交回复
热议问题