Android button tutorial
Saturday, January 31st, 2009 - 9:20 pm - Android
A lot of people have found this site by searching for an Android button tutorial, so here it is.
- This tutorial assumes that you already have an activity and are using an XML layout.
- Open the layout XML and add the button element. Assign an ID with the “@+id” operator. The + tells Android to generate an ID for this element so that you can reference it in your Java files.
- This is an example. Your layout and text elements will probably be very different. In this example case, the ID of the button is “close”.
<Button android:id="@+id/close" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="@string/title_close" />
- This is an example. Your layout and text elements will probably be very different. In this example case, the ID of the button is “close”.
- Open the activity class. Add a class property to hold a reference to the button.
private Button closeButton;
- If you haven’t already, override the onCreate method.
@Override protected void onCreate(Bundle savedInstanceState) { }
- For this example, we don’t need the saved instance state, so ignore it.
- Now, in the onCreate method, attach a listener to the click event for the button. This example will call “finish()” on the activity, the Android analog of clicking the close button on a window.
- Here’s a short description of what’s happening.
- First, get the button ID. The ID created earlier in the layout, “close”, is compiled by Android and assigned a unique integer ID which is available to the application through the “R” class, which I assume is short for “Resources”.
- Request a reference to the button from the activity by calling “findViewById”. The button has to be retrieved from the activity because while an ID is unique in an activity, it is not unique among all activities.
- Assign the retrieved button to an instance variable so that if you need it later, you can easily find it without having to query for it again.
- Create a class implementing “OnClickListener” and set it as the on click listener for the button.
As UI elements go, buttons are some of the simplest. Later, I’ll write about menus and dialogs, which aren’t so easy.




I am trying to figure out how to make and lay out buttons for the Android screen without making them in XML. Is this possible, and if so, how?
This website is great. I like it.(www.linkspirit.net)N_X_D_S.
this.buttonExeB = (Button)this.findViewById(R.id.buttonExe)
this.buttonExeB.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
Doesnt work 🙁
Hi!
I would like to know the simplest explanation of how to make a simple button(widget) in layer1 that will lead to layer2 when pressed.
Please help!
I tried to google it but no luck, everyone likes to complicate things that you can´t understand.
Hello Friend
Can u anyone tell me how to redirect the page on click the button… i have develop 2 applications
* app1
* app2
when i click the button in app1 i want to open the second app(app2)
Just remove the @Override above:
public void onClick(View v) {
finish();
}
and make sure that your class should implement the interface onClickListener
Txs!
Instead of new onClickListener(), it has to be new View.onClickListener(). Just spent 30 minutes trying to figure out the exact same error. Hope this helps!
how can i give to a button a pen with color red
Im sandhya how to create a image in a classs
hi ,when orientation of sceen changed ,haw can display athor layout with xml
please help 🙂
this is a very helpful tip for the android development beginers thanks 🙂
Hey,
Nice blog!!
I think shipra , you should use intent inside the button click event for traversing from one page to another.
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,destination.class);
startActivity(intent);
}
});
Hope this was helpful.. I’ve also discussed about intents in my humble blog http://androiddesk.wordpress.com/2011/12/24/explicit-intent/
May be you can go through it if you find it useful.
Thanks and Regards
Deepthi
hello everyone.
i m getting error again nd again. can u please help me.
“Unfortunately, E-Book has stopped”
how can i transfer command from one page to another page using button please help me.
Try changing to Java 1.6 instead of 1.5 from eclipse. That should solve this issue.
Im getting error messages in eclipse telling me that I need to remove the @Override above:
public void onClick(View v) {
finish();
}
because it must override a superclass method…
Thanks for the really simple description. It really helped to clear some things up that I was struggling to get my head round!
Hey this tutorial is quite helpful and works for one Button. But when I add a second one the App crashes, can you tell me what I am doing wrong?
public class RelationshipActivity extends Activity {
/** Called when the activity is first created. */
private Button OptionsButton;
private Button SaveButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SaveButton = (Button)findViewById(R.id.btnSave);
OptionsButton = (Button)findViewById(R.id.btnOptions);
SaveButton.setOnClickListener(new OnClickListener(){
public void onClick(View save) {
setContentView(R.layout.main);
}
});
OptionsButton.setOnClickListener(new OnClickListener(){
public void onClick(View options) {
setContentView(R.layout.options);
}
});
}
}
please… finish(); ist just an example!
Change the line:
finish();
into:
// place your code here
and it will run
can u check dis…
package Splash.screen.user;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class mainmenu extends Activity {
/** Called when the activity is first created. */
public Button closeButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.options);
this.closeButton = (Button)this.findViewById(R.id.close);
this.closeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
its showin error for the setonclicklistener()
this is my code….
public class mainmenu extends Activity {
/** Called when the activity is first created. */
public Button closeButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.options);
this.closeButton = (Button)this.findViewById(R.id.close);
this.closeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
but i m getting error for setOnClickListener saying this method is not applicable!!! nd options.xml is the page i want to link to..
PLZ HELP!!!
Hi, am new to android.the main.out.xml file will be create automatically when i was edit my main.xml file.it show the error message to me.i cont delete this main.out.xml file.y this fill was generated automatically and how will i delete this file from my project.what is the solution of this problem.plz help me.thank u………
What about making a class for a mineButtonMatrix and one for mineButton how hard can it be.
Make entry in menifest file for other activity
Thanks a ton, m just a beginner, this helped me alot
i am building a minesweeper app for android and i have some questions How to attach mines on buttons and how to build a rundom class to attach mines on buttons????
hi ,
i have written a program in which on clicking an imagebutton a sound should come and when i click a normal button it should go to another activity.image button is working fine but when i click normal button it is showing error.
package com.android;
import java.io.IOException;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
public class S2Activity extends Activity implements OnClickListener,MediaPlayer.OnCompletionListener {
MediaPlayer mp;
private ImageView button1;
Button btn;
private Random randomInt;
private int buttonPressed;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (ImageView) findViewById(R.id.ImageButton01);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
button1.setOnClickListener(this);
randomInt = new Random();
}
public void onCompletion(MediaPlayer mp)
{
}
public void onClick(View v) {
/*mp = MediaPlayer.create(this, R.raw.button);
mp.setOnCompletionListener(this);
mp.seekTo(0);
mp.start(); */
// Play only one sound at a time
if(mp != null) mp.release();
// Find which ImageButton was pressed and take appropriate action
switch(v.getId()){
// The first button
case R.id.ImageButton01:
mp = MediaPlayer.create(this, R.raw.button);
buttonPressed = 1;
mp.setOnCompletionListener(this);
mp.seekTo(0);
mp.start();
break;
// The second button
case R.id.button1:
Intent intent=new Intent(S2Activity.this, second.class);
startActivity(intent);
break;
}
}
}
can any one please help
Hi ,
I want details about button when if single lick it displays “a” and double click it will displays”b”
hi ur tutorial very well …
from mohan
i read this site ..very well i will improve my knowldge…thank Q.. for develop android tutorial
I v’e face one proble how to send data one page to another page plz send me the code as early as possible
just replace this.setContentView() amd this.closeButton as setContentView() and closeButton.thats it, your problem is solved….
just by remove implements OnClickListener, you can solve your problem…
I also get the “Button01 could not be resolved error.
Button01 is defined in the main.xml file
I am using Eclipse.
The suggestions eclipse gives me are not helpful.
Change “public class AndroidTest extends Activity implements OnClickListener” to just “public class AndroidTest extends Activity”, and try.
you can modify the touched listener, or you can change the device for touchdown and touchup. So in your touchdown imageview you change the background image form picture one to picture two. Then on touchup you change the imageview background back to the original image.
package com.testing;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Testing12345Activity extends Activity {
private Button closeButton;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) { {
this.setContentView(R.layout.layout);
this.closeButton = (Button)this.findViewById(R.id.close);
this.closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
}
This is my source code. And I got a forceclose error.
Kindly help
package universitaet.anwendung;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
//import android.widget.Toast;
public class FIM_APPActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private Button lehre;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lehre = (Button) findViewById(R.id.imageButton1);
lehre.setOnClickListener(this);
}
@Override
public void onClick(View v) {
lehre.setText(“Hallo”);
}
}
Why does it not run?
I am trying the above code which I see on a lot of sites, but I can’t get it to compile.
Here is my code:
package com.example.androidtTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class AndroidTest extends Activity implements OnClickListener
{
Button btnBell;
TextView txtHorn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnBell = (Button)findViewById(R.id.btnBell);
txtHorn = (TextView)findViewById(R.id.txtHorn);
btnBell.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
txtHorn.setText(“Ringing the bell”);
}
});
}
I get the following errors:
1. The method onClick(View) of type new View.OnClickListener(){} must
override a superclass
2. The type AndroidTest must implement the inherited abstract method View.OnClickListener.onClick
What am I doing wrong?
You can use in two ways 1st at design time and 2nd at run time
code of button.xml
hi,i,m facing the problem of button,i want to use same button for multiple use.when we hold button then should display other image and when release then should previous image . how can we implement this please give suggession..
hi. you can create button dynamicaly by sml or by code, choice is yours,
it depends upon the requirement.
In android you can easily make dynamic things using XML.
Thanks
if you want futher any info you can mail me..
hi,
i want to know hoe to put a simple button in android application.
plase help me. thanks to all.
Hello Dear, I am facing the problem of addition of check box while click on checkbox it display the results in the text field i do it for one check box but i want that when i click on two or more than two check box then the total of check box value display and again if we click one the check box then it substract the value from the total. I have following code please help me i tried a lot but unable to get the result.
public class EChalanActivity extends Activity {
public CheckBox checkbox1,checkbox2,checkbox3,checkbox4,checkbox5;
TextView txtpayment;
EditText payment;
int sum;
int ihalmet;
int crsroad;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
this.setTitle(“EChalan”);
setContentView(R.layout.main);
payment = (EditText)this.findViewById(R.id.payment);
checkbox1 = (CheckBox)findViewById(R.id.chkHelmaet);
checkbox2 = (CheckBox)findViewById(R.id.crossroad);
checkbox3 = (CheckBox)findViewById(R.id.rcchallan);
checkbox4 = (CheckBox)findViewById(R.id.triply);
checkbox5 = (CheckBox)findViewById(R.id.pollution);
checkbox1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// ihalmet = 100;
payment.setText(“100”);
if(checkbox1.isChecked()){
payment.setText((payment.getText()));
}else{
payment.setText(“”);
//ihalmet = 0;
}
}
});
checkbox2.setOnClickListener(new OnClickListener() {
public void onClick(View v1) {
// TODO Auto-generated method stub
// crsroad = 200;
payment.setText(“200”);
if(checkbox2.isChecked()){
payment.setText((payment.getText()));
}else{
payment.setText(“”);
//crsroad = 0;
}
}
});
payment.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// payment.setText(sum);
payment.setText(“300”);
if(checkbox1.isChecked()|| checkbox2.isChecked()){
// sum = 100 + 200;
payment.setText(payment.getText());
}else{
payment.setText(“”);
}
}
});
Thx for the info, really help me out
how to add button dynamically in android?
Hi there, if anyone could help me out please here. I am facing a problem and can not find the solution for this … My code is the following and i cant seem to find the errors but its just when the splash screen is exited towards the main page, just top button works, others don’t … but when tapped that button and return from there then all the buttons work. I want them all to work
package net.xuting;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class xutingMenu extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// button 1
Button btn_live_tv = (Button) findViewById(R.id.btnLiveTv);
btn_live_tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(“net.xuting.LIVETV”));
//button2
Button btn_Favorites = (Button) findViewById(R.id.btnFavorites);
btn_Favorites.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(“net.xuting.FAVORITES”));
}
});
//button 3
Button btn_Featured = (Button) findViewById(R.id.btnFeatured);
btn_Featured.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(“net.xuting.FEATURED”));
}
});
//button 4
Button btn_Video_On_Demand = (Button) findViewById(R.id.btnVideoOnDemand);
btn_Video_On_Demand.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(“net.xuting.VIDEO_ON_DEMAND”));
}
});
//button 5
Button btn_Search = (Button) findViewById(R.id.btnSearch);
btn_Search.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(“net.xuting.SEARCH”));
}
});
//button 6
Button btn_Settings = (Button) findViewById(R.id.btnSettings);
btn_Settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(“net.xuting.SETTINGS”));
}
});
}
});
}
}