- Get link
- X
- Other Apps
There are three ways to setup a listener in Android:
- android:onClick="myClickHandler"
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
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()
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.
- Get link
- X
- Other Apps
Comments
Post a Comment