Android button tutorial

A lot of people have found this site by searching for an Android button tutorial, so here it is.

  1. This tutorial assumes that you already have an activity and are using an XML layout.
  2. 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.
    1. 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" />
  3. Open the activity class.  Add a class property to hold a reference to the button.
    private Button closeButton;
  4. If you haven’t already, override the onCreate method.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    }

    1. For this example, we don’t need the saved instance state, so ignore it.
  5. 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.
protected void onCreate(Bundle savedInstanceState) {
  this.setContentView(R.layout.layoutxml);
  this.closeButton = (Button)this.findViewById(R.id.close);
  this.closeButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
      finish();
    }
  });
}
  1. Here’s a short description of what’s happening.
    1. 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”.
    2. 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.
    3. 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.
    4. 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.


  1. Balaji j says:

    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………

  2. Akki says:

    Thanks a ton, m just a beginner, this helped me alot

  3. Anonymous says:

    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????

  4. sneha says:

    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

  5. Anonymous says:

    Hi ,

    I want details about button when if single lick it displays “a” and double click it will displays”b”

  6. rajasekhar says:

    hi ur tutorial very well …
    from mohan

  7. rajasekhar says:

    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

  8. Richard says:

    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.

  9. Anonymous says:

    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

    • hai says:

      just replace this.setContentView() amd this.closeButton as setContentView() and closeButton.thats it, your problem is solved….

  10. michael says:

    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?

  11. Harvy says:

    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?

    • Sandeep says:

      Change “public class AndroidTest extends Activity implements OnClickListener” to just “public class AndroidTest extends Activity”, and try.

    • hai says:

      just by remove implements OnClickListener, you can solve your problem…

  12. dilip kumar chaudhary says:

    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..

    • mrj05hua says:

      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.

  13. mayur manvar says:

    hi,
    i want to know hoe to put a simple button in android application.
    plase help me. thanks to all.

  14. Amit Kumar says:

    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(“”);
    }
    }
    });

  15. punzz says:

    Thx for the info, really help me out

  16. nisha says:

    how to add button dynamically in android?

    • Deepsan says:

      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..

  17. Hassan says:

    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”));
    }
    });
    }

    });
    }

    }

  18. Anonymous says:

    Its working .Am a beginner its really helpful

    • Huzefa says:

      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()

  19. 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.

  20. rregy says:

    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

  21. FancyD says:

    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???

  22. Michael Zick Doherty says:

    You’re missing the part about the strings.xml….

  23. sim says:

    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!

    • MrSqueezles says:

      You can define i as final.

      for(final int i=0; i < 3; i++){

    • sim says:

      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.

    • MrSqueezles says:

      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();
      }

  24. […] 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: […]

  25. paul says:

    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..

  26. jayanth says:

    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?

  27. Ric says:

    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?

  28. Arnaud says:

    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.

    • MrSqueezles says:

      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.

  29. Chip says:

    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”);
    }
    }

    • MrSqueezles says:

      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.

    • vinodkumar says:

      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

    • MrSqueezles says:

      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.

  30. David Saunders says:

    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.

  31. Rizwan says:

    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!!

  32. beginner says:

    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.

    • MrSqueezles says:

      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.

  33. Tallal says:

    Gianluca, hey is your name Favali , if yes I m tallal from mobile complete device anywhere do u remember ?

  34. My android app is crashing , the code of my application is here: http://pastebin.com/EECYFkkC

  35. Michael says:

    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

    • MrSqueezles says:

      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.

  36. MrSqueezles says:

    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

  37. Michael says:

    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

  38. Michael says:

    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

    • MrSqueezles says:

      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

  39. Irfan says:

    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?

    • MrSqueezles says:

      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" />

  40. Dj says:

    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

  41. ib says:

    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.

    • Anonymous says:

      add your image to drawable.
      then make change in androidmenifest file.
      tover there u have to give image name instead of icon.

  42. kanna says:

    Hi! can u suggest me the best way to drag,zoom same image.

    • MrSqueezles says:

      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.

  43. Arunabh Das says:

    Can a button be text-only (i.e. no background) ?

    • MrSqueezles says:

      Button inherits setOnClickListener from android.view.View. You can set a click listener on anything you display. If you want a button that is just text, use a TextView and set a click listener on it.

  44. em says:

    any idea how to change button image when click ? and when let go it return to normal?

  45. RayWorld says:

    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);

    }

    }

    • MrSqueezles says:

      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.

  46. Gianluca says:

    Thanks, very usefull

  47. Ale says:

    Evan: this.setContentView(R.layout.main) is missing.

  48. Jaggy says:

    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 ?

  49. Evan says:

    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

    • MrSqueezles says:

      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;

Leave a Reply