Click here to Skip to main content
15,888,968 members
Articles / Programming Languages / Java
Tip/Trick

Adding OnClick Event for button in XML

Rate me:
Please Sign up or sign in to vote.
4.00/5 (4 votes)
8 Oct 2013CPOL 46K   2   1
Code for implementing a click event for button in Android.

Introduction

I am sharing a piece of code for implementing a click event for button in Android.

Background

I had seen almost all android developer using same method for implementing click event for a button. While browsing over the internet I had gone through another method, which I think was much simpler than conventional method.

Using the code

The conventional method I have seen is like this: 

If we have a button with ID Button1 the XML code will be like this:

XML
<Button android:id="@+id/Button1"  
android:layout_marginRight="10dp" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_marginRight="10dp" 
 /> 

We can add Java code like this: 

Java
Button b1 = (Button)findViewById(R.id.Button1);
b1.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
//Code to implement 
}
});

Instead of this I can add click event in XML itself like this:

XML
<Button android:id="@+id/Button1"  
android:layout_marginRight="10dp" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_marginRight="10dp" 
android:onClick="clickEvent"
 />  

In Java code I need to do this:

Java
public void  clickEvent(View v)
{
//Code to implement 
}

Points of Interest

I think this method is simpler to implement.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior) Applexus Technologies
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
XOIII16-Oct-13 21:49
XOIII16-Oct-13 21:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.