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.




Its working .Am a beginner its really helpful
I am still confused with the usage of javascript like the picture above, is there anything easier?
but this can add to the experience for me, maybe good to try.
Hello everyone..i am new to the android development.
We have a training and the problem goes like this
****************
#Declare the intent with the appropriate filter specified (ACTION_VIEW, ACTION_WEB_SEARCH, and so on).
#Attach any extra information to the intent required to run the activity
#Pass this intent to startActivity().
#Create a class that extends the ListActivity class instead of the Activity class
#Prepare a list of Strings with 5 items like the example below:
#static final String[] ACTIVITY_CHOICES = new String[] {
“Open Website Example”,
“Open Contacts”,
“Open Phone Dialer Example”,
“Search Google Example”,
“Start Voice Command”
};
#Call getListView() from ListActivity to get the ListView
#Call setChoiceMode(ListView.CHOICE_MODE_SINGLE) if you want to have a single mode for choosing items
#Set the listener for the item click using setOnItemClickListener(OnItemClickListener)
#Override onItemClick(Adapter, View, int position, long id) and put your actions to each selection
#Call getListView() from ListActivity to get the ListView
#Call setChoiceMode(ListView.CHOICE_MODE_SINGLE) if you want to have a single mode for choosing items
#Set the listener for the item click using setOnItemClickListener(OnItemClickListener)
#Override onItemClick(Adapter, View, int position, long id) and put your actions to each selection
#Call setListAdapter(ArrayAdapter)
#Use ArrayAdapter as the parameter
#Create a switch statement using the Intents below for each corresponding item in the list:
0: startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(“http://www.android.com/”)));
1: startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(“content://contacts/people/”)));
2: startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(“tel:12125551212”)));
3: Intent intent= new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, “superman”);
startActivity(intent);
4: startActivity(new Intent(Intent.ACTION_VOICE_COMMAND));
new ArrayAdapter(context,
textViewResourceId, [] objects)
******************************
++++This will be the problem. I dont know how to do it..please help me to do the job..Thank you in advance
It’s impossible for me to tell what’s going wrong. Take a look at the stack trace to see what your error is.
I keep trying the code and everytime I run it, it force closes. I added an asyncTask class but that didn’t help. What version of of the Droid are yu running this under, 2.1 or 2.2 or is it an Google API version 8???
add your image to drawable.
then make change in androidmenifest file.
tover there u have to give image name instead of icon.
You’re missing the part about the strings.xml….
I’m sorry. I wasn’t thinking. This is more of a Java question than Android and the solution depends on what you’re trying to do. Is there a reason you’re logging the array index of the button? If so, you can do something like this. This is not an ideal solution, though, because it’s using a concurrent class. You can use something else that provides the same function. I’d suggest not referencing i from the click method.
final AtomicInteger value = new AtomicInteger(0);while (value.incrementAndGet() < 3) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(value.get());
}
};
runnable.run();
}
thanks MrSqueezles,
when i define i as final, eclipse underscores j++ and tells me not to assign i. how shall i do?
>The final local variable j cannot be assigned. It must be blank and not using a compound assignment
any comments are appreciated.
You can define i as final.
for(final int i=0; i < 3; i++){
nice tutorial.
would you tell me how to pass parameters other than View v to OnClick()?
i’d like to generate three buttons which respectively outputs “0”, “1” or “2” as debug message. but following code doesn’t work because variable i is not referable from onClick().
Button btn[]=new Button[3];
for(int i=0; i<3; i++){
btn[i].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.v("msg", "btn"+i+"is pressed.");
}
});
}
thanks in advance!
[…] While I was working on setting up a button in my UI, I googled for some code on setting up the click event-handler. What I found was this gem: […]
hello..
i have a problem in android..i create an application and i have a tab menu..i create a button and when i clicked there this change me the interface (in xml). back there i have put another button to go back to the previous xml interface.. since then its all ok..!! but after this the button at the first interfacce didnt do anything…i think it takes the ids for the button at the second interface so i havent the control of the first button… what can i do ?? ..i dont know if you understand the situation :p ..i am sorry about my english…i am waiting for a response..
hi,
i’m the begginer for this.please help me out.i dont know how to insert a button , i have followed the tutorial but i didnt get anything.can u please let me how to insert button using .xml?
I figured out how to create the button, but I wasn’t able to figure out how to point that button to a website. Any ideas?
Thank you, Vinodkumar.
That definitely works, but I don’t see it being more valuable than writing separate listeners. It limits your ability to reuse code and is very procedural and non-OO.
More importantly, your Activity is not a click listener. Logically, clicks are separate actions. I assume that in the future, Android will support Java 7 closures as click listeners. If and when that happens, passing onClick code to buttons will be much simpler in every way than having Activities that implement OnClickListener.
you should try this it works.
public class Translate extends Activity implements OnClickListener {
public void onClick(View v) {
switch (v.getId()) {
case R.id.about_button1:
Intent i1 = new Intent(this, About1.class);
startActivity(i1);
break;
public class About1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.submitting);
if any problems then reply
[…] Vía / Dev Notes […]
Hi Chip.
You might take another look at the tutorial. Don’t set the click listener to “this”. Declare the onClick as an anonymous inner class. Set the onClick event of the button to that. That way, you have two separate onClick handlers, one for each button.
Also, take “implements OnClickListener” out of the declaration of the Activity.
Hi Arnaud.
Inner classes are compiled, just like any other classes. You can see that in your compiled code. You’ll have two class files with the same name, but one will end with a 0. That’s the inner class. If you’re writing a reusable function, make it a separate class. Otherwise, an anonymous inner class is fine. An inner class works too. If it’s a complex activity, a non-anonymous ininner class may make your code easier to read. For performance, though, there isn’t any difference.
Hello,
I have a question for MrSqueezles, you said earlier it was best practice to use an anonymous inner class.
However I read that “this will consume more resources because this instantiates a new object and class information for the object will need to be stored as well.” And that “making the class extending the interface has a clear performance benefits in that you don’t have to load extra classes, which reduces your memory footprint and load time. In this option you would be able to register SimpleJokeList to respond to Click events from many different UI Controls”
They were also saying that “this is actually very common in Android applications due to the need to design for performance imposed by limited resources.”
What do you think about that, I don’t really know what path to follow.
Thanks for the great info! My code below seems to be working but I am stumped as to how to differentiate which button has been pressed from my Activity. I see in the log each time I press any button that the handler is invoked but I need to have different results for each of the different buttons that might be pressed.
I am guessing that I need to implement some addtional code in the “onClick” method somehow analyzing “v” but I can’t seem to figure out exactly what I need to do with it.
Advice?
Thank you!
Chip
package com.example.HelloAndroid;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelloAndroid extends Activity
implements OnClickListener
{ /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Action1On_button = (Button) this.findViewById(R.id.Action1On_button);
Action1On_button.setOnClickListener(this);
Button Action1Off_button = (Button) this.findViewById(R.id.Action1Off_button);
Action1Off_button.setOnClickListener(this);
Button Action2On_button = (Button) this.findViewById(R.id.Action2On_button);
Action2On_button.setOnClickListener(this);
Button Action2Off_button = (Button) this.findViewById(R.id.Action2Off_button);
Action2Off_button.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i(“onClick”, “BEGIN”);
Log.i(“onClick”, “END”);
}
}
Hi, I am a beginner also and I am trying to write my first app. I tried to follow your tutorial but I am not sure where to place the class property for the button. I know you said open the activity but I am not sure where to place it. I have also been looking at the tutorials on developer.android.com and they are not working either. I want to display the name of my application with four buttons on the bottom 2 rows of two. But I cannot even get one to work without Eclipse giving me errors. I have the text displaying though. I am also trying to get the name of my app to be centered on the screen. I am pretty sure it probably needs to be specified in the XML, but I do not know the parameter to use. Do you?
Here is my MyApp.java code:
package com.android.FSA;
import android.app.Activity;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MyFSA extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setTextSize(75);
tv.setText(“My Field Service Activity”);
setContentView(tv);
//setContentView(R.layout.starttime);
this.starttimeButton = (Button) this.findViewById(R.id.starttime);
this.starttimeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Perform action on click
finish();
}
});
}
}
Here is my main.XML:
I would appreciate it if you could point out where I am going wrong.
Hi Can someone please help me with this.
I have an about button in my application which when clicked shows a text in scroll view layout. It is invoked in another activity.
Now i want to place a cross just like in windows on top right most side, which when clicked should close this page.
I have understood the above procedure but don’t want to get it done by pressing this Mighty sized button. Is there anyway to do this by clicking (say) a small icon on top-right corner of page or may be by clicking a Close Text at the bottom of the page?
Please someone help!!
beginner, take a look at the example. You know a button was clicked when the click handler is called. You don’t have to check a property.
If you want, you can subclass Button and add that function. Maybe you’re looking for a toggle button.
hi,
I am new to android programming. I have 2 activity pages.
On my first activity page i have 3 image butotns. Depending on what button is clicked the next activity page should display the result.
I am not able to find a suitable Button property which checks whether the button is pressed or not. I tired isclicked() and ispressed() but none of them is giving a correct result.
Please reply soon.
Gianluca, hey is your name Favali , if yes I m tallal from mobile complete device anywhere do u remember ?
My android app is crashing , the code of my application is here: http://pastebin.com/EECYFkkC
Sorry for the delay, Michael. I’ve been busy unpacking after moving. If you check it in to a public repository, I’ll take a look.
Ok Connor I will give it all a try. Will take me however a bit to get through this all…LOL Thanks for all the help. Another thing, would it be possible to send you my Eclipse Project and if you had time to take a glance at it. Maybe give me some suggestions as to what I am doing wrong or what I could improve on?
Thanks,
Michael
I’m happy to help. I haven’t done anything like this before and I’m at work, so I can’t mock something up, but I can tell you how to get started.
First, I’d recommend not doing it this way. Read below for my suggestion.
Check out the View documentation http://developer.android.com/reference/android/view/View.html You can setOnClickListener for a view. Also look at FrameLayout http://developer.android.com/reference/android/widget/FrameLayout.html I would recommend creating a view with no background or a transparent background and an onClickListener. Put it in a FrameLayout with the exit image so that the transparent view is in front. The FrameLayout will have to be confined to the size of the exit image.
I would recommend a different approach, though. Put the board in a LinearLayout with vertical orientation. Put the board on top exit button below. (http://developer.android.com/guide/topics/ui/layout-objects.html) That way, you can set the exit image’s onClickListener. You could also make the squares on the board separate layout objects and use a 3×3 table to lay them out. Even further than that, Android has great support for vector graphics, so your game could scale to any screen size. If you do this, look at http://www.connorgarvey.com/blog/?p=1 for information about laying out items in a grid. Maybe start with buttons and then move to vector graphics 🙂 Here’s some information about vector graphics. Yours will not be nearly as complex as these (at first). http://developer.android.com/guide/topics/graphics/2d-graphics.html
Hi Connor,
Thanks for your reply. Being new at this all I am really struggling to get this to work but I am enjouing it as I learn. I was working on something very simple called “Tic Tac Toe”. LOL…I have a graphic background and at the bottom I have the word “EXIT”. Of course it is only part of the grahic and does nothing. So I thought I could but a button over the word and have it function as my “exit” button. I would like to have it work when I click in the area of the button button it is of course covering up my graphics and was hopeing I could make it invisible on my screen. But you mentioned something about a “Transparent button”….wish I could cut and paste a picture of my screen in this blog so you coulod see what I am talking about….
So what exactly is a transparent button?
Thanks for your help Connor
Michael
Hi Michael.
I’m not exactly sure what you mean, but you could do something like that in a few different ways. If you have a graphic that can be clicked to exit, assign the click listener to the graphic. You could also use FrameLayout to put a transparent button over the entire screen and assign a click listener to that.
I’ve never done the second one. If you do it, I’d be interested to hear how it worked out.
Connor
Hi There All,
Just a short question, can I have a button perform a certain function such as “exit” but at the same time have it not visible on my page? On my page I have some grahics and would like to have the function of “exit” but would not like to have the button cover up my graphics such as where I have the word “EXIT”
Thanks for any help,
Michael
Starting an activity looks something like this.
this.startActivity(new Intent(Intent.A_URI, getIntent().getData()));or this
startActivity(new Intent(SomeIntents.A_URI, getIntent().getData()));You also have to set the activity up in your Android manifest.
<activity android:name="AnActivity" android:label="@string/message_label"><intent-filter android:label="@string/resolve_label">
<action android:name="org.someapp.someintents.A_URI" />
Hi,
The question is that I am trying to login screen for my application. If i press a login button, how it is possible to oepn a new screen with the username and password text boxes. Any body can help me?
link=(TextView)findViewById(R.id.sample);
// link.setOnClickListener(this);
link.setOnClickListener(new TextView.OnClickListener()
{
public void onClick (View v)
{
startActivity(new Intent(radiobutton.this,kk.class ));
}});
}
I am trying to do,when i click the text view it should redirect to kk class..like links…..not with the buttons with textview only
hi, i have been trying to use an icon for my menu not sure how. i have tried using setIcon(R.drawable then the image name).
can someone assit.
I’m not sure what you mean. Do you want a draggable button? I stick to the standard Android view classes, so I would have to look into that.
ButtoninheritssetOnClickListenerfromandroid.view.View. You can set a click listener on anything you display. If you want a button that is just text, use aTextViewand set a click listener on it.Hi! can u suggest me the best way to drag,zoom same image.
Can a button be text-only (i.e. no background) ?
any idea how to change button image when click ? and when let go it return to normal?
Hi Ray.
First, your activity shouldn’t implement OnClickListener. It’s much better design to use an anonymous inner class, as in the example.
I think your problem may be that you’re setting the content view twice. It may be that when you set it the second time, you’re clearing the onClickListener. Remove the second setContentView and it may work.
can anyone help me? I’m trying to change a text in a textview when a button is clicked but it doesn’t work… here is my code.
import java.util.LinkedList;
import java.util.List;
import piero.RayWorld.projects.exam.R;
import piero.RayWorld.projects.exam.R.id;
import piero.RayWorld.projects.exam.R.layout;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity implements OnClickListener {
TextView tx;
Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.simplegpslayout);
Context context = getApplicationContext();
this.b = (Button) findViewById(R.id.Button01);
tx= (TextView) findViewById(R.id.TextView01);
this.b.setOnClickListener(this);
this.setContentView(R.layout.simplegpslayout);
}
@Override
public void onClick(View v) {
tx.setText(“ciao);
}
}
Thanks, very usefull
Evan: this.setContentView(R.layout.main) is missing.
i have followed this tutorial and added this code
mport android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ArrangeMe extends Activity {
private Button button1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.button1 = (Button)this.findViewById(R.id.button1);
this.button1.setOnClickListener(new OnClickListener() {
//@Override
public void onClick(View v) {
finish();
}
});
setContentView(R.layout.main);
}
}
my layout xml looks like
i get this.button1 as null and eventually crashes the app.. whats going wrong ?
Hi Evan,
Remember to import the Button class. I highly recommend using Eclipse. It’ll underline the exact location of this error and offer solutions. If you are using Eclipse and you see the red underline under something, look for a little light-bulb in the left margin and click on it. To fix your problem, add the button import.
import android.widget.Button;
I keep getting “Button cannot be resolved as a type”
What am I doing wrong?
Here’s my main code:
__________________________________________________________
package com.clouds;
import android.app.Activity;
import android.os.Bundle;
public class welcome extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
this.closeButton = (Button)this.findViewById(R.id.close);
this.closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private Button closeButton;
}
And here’s my XML Code:
main.xml
_________________________________________________
strings.xml
__________________________________________________________
Welcome to Cloud Sketch
Cloud Sketch
Close