Android Basics : Why an onClickListener is better than android:onClick

In your App you might be having UI elements like buttons on click of which some action happens in the background.

Let’s take a button for example.


There are two ways to handle events on Button click. One is to define an android:onClick attribute in the layout xml file and specify the method in the Java class.


The problem with this approach is – if you have buttons defined in a Fragment then you need to define corresponding methods in the Activity class. This will lead to tight coupling between Activity and Fragment.

To avoid this use a onClickListener.

For this you need to implement an onClickListener and bind the Button to this.

Follow the video and refer to the source code here to understand this better.