Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Adding OnClick Event for button in XML

4.00/5 (4 votes)
8 Oct 2013CPOL 46.9K  
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)