Android UI How to - Button XML attribute click handler








We can use xml attribute to specify click event handler for a button.

The following code shows the XML for a Button where you specify an attribute for the handler, plus the Java code that is the click handler.

<Button   ...    
          android:onClick="myClickHandler"    
          ...  />

Java code to handle the click event.

public void myClickHandler(View target) {
    switch(target.getId()) {
       case R.id.button1:
       ...

The handler method will be called with target set to the View object representing the button that was clicked.

The switch statement in the click handler method uses the resource IDs of the buttons to select the logic to run.

In this way you won't have to explicitly create each Button object in your code, and you can reuse the same method across multiple buttons.





Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//from   w  w  w.  j  a  v a 2 s .c  o m
    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OK"
        android:onClick="myClickHandler"
        />

</LinearLayout>

The following Java code implements the action listener.

package com.java2s.app;
//from  w  ww  .  ja va  2 s  . co  m
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
    public void myClickHandler(View target) {
        System.out.println("java2s.com event");
        if(target.getId() == R.id.myButton) {

        }
    }
}