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.

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/testButtonId"
    />

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.

android:onClick="testMethod"

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.

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s