Button XML attribute click handler

Description

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  ww .  ja v  a 2s .  c  om*/
    <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;
// www  .  j  a  va 2s  .c o 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) {

        }
    }
}




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView