I started program little bit in android, I have 3 buttons in a single activity.
I saw some example codes that assign the same OnClick
event to all the buttons (even if they perform completely different action) and in the method Switch(id)
case case case...
What is the better approach? one onClick
method and switching or a lot of methods, one for each button?
Thanks.
Little addition to @Nguyen answer.
This could be useful, if you don't want to initialize the button variable, but want to track button click event. Thanks!
If you want to reduce the coding lines then use
View's OnClick() with switch statement
and if you want to handle separately all click (for easily understanding and maintaining code) then use separate allbutton's onClick().
Update:
If you have declared Buttons in your Activity layout xml file, than write attribute
android:onClick=""
with same method name for all buttons and implement that method in your activity. Now you have one method for all buttons and in that method differentiate buttons with id.Example:
Now in your Activity implement
buttonOnClick
like,Or you can apply same switch case for dynamically added buttons in your activity, like instead of
buttonOnClick
you have to use implemented View's OnClickListerner'sonClick
.Method in .class
I think registering
onClick
in xml (layout) is better approach.EDIT:
Found related threads :
Use this way:
Here is the good way.