Best practice for defining button events in android

Why not registering onClick event in the XML layout and then handle it in the code. This is how I would do it:

<Button
android:id="@+id/my_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:onClick="onBtnClicked">
</Button>

and now create a method that would handle clicks

public void onBtnClicked(View v){
    if(v.getId() == R.id.my_btn){
        //handle the click here
    }
}

Alternatively, you can set the OnClickListener individually for each item in the code. Then use the if/else or switch statements to determine the origin.

This way you can have one method that handles all buttons from one layout.

UPDATE:
Although this is a valid approach I would strongly recommend the second option. It’s cleaner and easier to maintain especially when you work with fragments.

Leave a Comment