How to handle a button being clicked in Android?

前端 未结 2 873
无人及你
无人及你 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:37

    The first two are the classic approaches. Which one you prefer is more of a general Java question than an Android question. The third one was added later to make things easier.

    Setting up a click listener on a button is very common task, but it requires quite a bit of boilerplate code. One way to reduce the amount of boilerplate is to share a single click listener between several buttons. While this technique reduces the number of classes, it still requires a fair amount of code and it still requires giving each button an id in your XML layout file. With Android 1.6, none of this is necessary. All you have to do is declare a public method in your Activity to handle the click (the method must have one View argument)

    Source

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题