Many Ways To Assign Click Event To Button On Android

 

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading...

 

Ho Ngoc Trang,  trangho214@gmail.com, is the author of this article and she contributes to RobustTechHouse Blog. 

 

Introduction

We can assign the click event to many different components such as Button, ListView, Dropbox and etc. When a component is assigned a click event, the component will do a specific task whenever it is clicked on. One of the most common components to assign click events to is a Button.

There are many tutorials to assign click events to buttons  but each of them has it’s own way to implement the click event. When I was a beginner Android programmer, I was very confused about which way is the right one, or why Tutorial A is different from Tutorial B when they might be doing the same thing.

In this article, I decided to list the four different ways I know to accomplish this.

 

1. Apply an onClickListener to the button in your activity

Declaring the OnClickListener within the call to the setOnClickListener method is common. A typical use of a push button in an activity is implemented like the following

main.xml

MainActivity Class

 

2. Define an onClick method in main.xml

Instead of applying an OnClickListener to the button in your activity, you can assign a method to your button in the XML layout, using the android:onClick attribute. In this attribute we specify the name of the method in Activity. This method will be invoked when the button is clicked.

main.xml

Then, add this method inside Activity (MainActivity.java). Method requirements: public, void and receives a View object as a parameter:

MainActivity Class

 

 

3. Implement View.OnclickListener interface in the Activity

The Activity itself can implement the OnClickListener. Since the Activity object already exists this saves a small amount of memory by not requiring another object to host the onClick method.  To assign click event to button on Android, this frequently seems like the recommended way.

main.xml

MainActivity class

 

 

4. Assign a variable of OnClickListener interface type to the button

In this way, we will declare a variable as a type of OnClickListener interface, then assigned it to the button.

main.xml

MainActivity class

 

 

Conclusion

Many roads lead to Rome to assign click event to button on Android. Depending on your code layout, feel free to choose which of the above methods to use.

 

Brought to you by the RobustTechHouse team (A top iOS and Android developer in Singapore).  If you like our articles, please also check out our Facebook page.

 

Recommended Posts
Contact Us

We look forward to your messages. Please drop us a note for any enquiries and we'll get back to you, asap.

Not readable? Change text. captcha txt
Chargebacks2Backlinks