Friday, August 5, 2011

Android Saved State Button Tutorial

Earlier I posted a tutorial on how to make a button respond to a single tap.  But what if you want a button to stay in its selected state after it has been tapped.  This is a tutorial on how to create a button that shows the user they have selected it.  You will learn how to add the xml code to your layout and the java behind it.


Step 1: Start a new Android Project
Click File>New>Android Project.  In the Project Nam: field enter Saved State Button Project.  Select the latest API level you are comfortable with (API10 for me).  In the Package name: field enter com.androgue.ssbutton.  In the Create Activity: field enter main (no caps) for the initial activity.  Click Finish.

Step 2: Add your Pic Resources
In order to show your user that they have selected a feature or button, you need to provide images for each of the two states.  For example, I used these two buttons below.

Add these pics to your res/drawable directory in your project.

Step 3: Add a Button to your main.xml
In the package explorer, browse to  res/layout/main.xml and click the main.xml tab at the bottom of the screen to view the code.  Replace the TextView code with the following code.

Step 4: Add the Java to your File
In the package explorer, browse to src>com.androgue.ssbutton>  Replace the code with the following.
package com.androgue.ssbutton;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class main extends Activity implements OnClickListener
 boolean check = false;
 Button btn;
    public void onCreate(Bundle savedInstanceState) 
        View ssbtn = findViewById(;
    public void onClick(View v)
      if (check == true)
       check = false;
       check = true;
      if (check == true)
      if (check == false)

Step 5: Run your App
Your app is now complete.  Start your favorite emulator and run the app.

Download the Source Code
com.androgue.ssbutton (zip, 52k)

No comments:

Post a Comment