Simple Button for Android – XML onClick + public method

Probably the simplest way to create Android Button. Create a new public method (e.g. goButtonClicked) and add it to your layout XML.
Prequisites: Android Hello World Explained
In Java, define a new public method that takes view as parameter.

public void goButtonClicked(View v) {
        // do stuff

In your XML file, create a new button. Name your method as onClick property for the button.

<Button android:text="Go!" android:onClick="goButtonClicked"

That’s it.
Below, a complete example code.

Complete Code Example for Simple Button


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
<Button android:layout_height="wrap_content"
 android:layout_width="wrap_content" android:text="Go!"
 android:onClick="goButtonClicked" android:id="@+id/goButton"></Button>

package com.botbook.simplestbutton;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class SimplestButtonActivity extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    public void goButtonClicked(View v) {
    	tToast("Go button clicked!");
    private void tToast(String s) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, s, duration);;

See also:
Android Reference: Button

Posted in Uncategorized | Tagged , , , , , | 4 Comments

4 Responses to Simple Button for Android – XML onClick + public method

  1. Mark says:

    Works great! Thanks, I was looking for an alternative to “System.out.println” for testing since i’m just beginning.

  2. Ali Genç says:

    This onclick method just not worked. When I clicked button, emulator gave an error and closing the application.

  3. Miguel Cunha says:

    I hav find a error on the code: ” android:layout_width=”fill_parent” “. Its says that its noot wee-formed, can you give some help?

  4. Marten says:

    Works great, thanks for instructions.