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"
android:id="@+id/goButton"></Button>
That’s it.
Below, a complete example code.
Complete Code Example for Simple Button
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Go!" android:onClick="goButtonClicked" android:id="@+id/goButton"></Button> </LinearLayout>
SimplestButtonActivity.java
package com.botbook.simplestbutton;
import android.app.Activity;
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. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
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);
toast.show();
}
}
See also:
Android Reference: Button
Works great! Thanks, I was looking for an alternative to “System.out.println” for testing since i’m just beginning.
This onclick method just not worked. When I clicked button, emulator gave an error and closing the application.
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?
Works great, thanks for instructions.