Reputation: 271
Rather than using a single onClick()
method for all the buttons in an Activity, and then using the switch statement to determine which button was clicked, I set different methods for different buttons in the
android:onClick
XML parameter. For example, for one button I set the onClick parameter to onClickCalculateButton
and for another button I set the onClick XML parameter to onClickNewFileButton
.
Is this a good coding practice?
Upvotes: 0
Views: 900
Reputation: 4651
There is no real convention in this case. I've seen good programmers do it this way or the other, and I'm guessing most people agree.
For buttons that are not straight forward (not in activity/fragment) and cant be used with ButterKnife I don't set the click listener in XML rather then implementing it at a specific class (activity/fragment/whatever) with switch-case and then referring to the specific method.
switch(view.getId()){
case R.id.button_one:
clickOnButtonOne(view);
break; ...
For buttons that I know their lifecycle (in fragment/activity) I use ButterKnife and use it annotation (
@OnClick(R.id.button)
Upvotes: 2
Reputation: 149
I would avoid using the android:onClick param in XML. As projects become larger it becomes more difficult to manage, especially when you are dealing with Fragments.
I follow the same convention you do for naming, but I create separate onClickListener classes for each button within the Activity or Fragment. Makes it easier for me to track which button does what as I can follow its source through Android Studio from onCreate.
However, you might be using the XML tags for the same reason I would which is creating less code. If that is the case, I would look into using ButterKnife (http://jakewharton.github.io/butterknife/). It uses annotations to generate the needed code later and is super clean.
Upvotes: 0