Android Nougat

Listeners and Callbacks

There are three ways to setup a listener in Android:

  • android:onClick="myClickHandler"
This calls the method myClickHandler(View v) in the Activity. It's importent to know that the Activity is responsible for this method. Even if you are using this in a layout of a Fragment.
  • implements OnClickListener
You must override the onClick(View v). If you have more Views, which are clickable, you can use this to bundle all code of the views in this method. This is better maintainable. Also it reduces Object creation. If you have multiple buttons, IMO this is better than associate multiple click listeners to the buttons.
onClick(View v){
    switch(v.getId())
    case R.id.button1:
       // do something related to this button 1
    case R.id.button2:
       // do something related to this button 2
    ...

}
  • setOnClickListener(new View.OnClickListener()
If you have one view set the listener directly for more readability by using an anonymous class. With this you mostly have the implementation of the listener in the scope of the view.
There is no real convention when to use the second or third approach. It's mostly opinion based . But be careful with the first approach, especially in Fragment scenarios.

Comments