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.

Preview


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 main.java File
In the package explorer, browse to src>com.androgue.ssbutton>main.java.  Replace the code with the following.
package com.androgue.ssbutton;

import android.app.Activity;
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;
 
 
 
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainpage);
        
        btn=(Button)findViewById(R.id.ssbutton);
        
        btn.setBackgroundResource(R.drawable.off);
        
        View ssbtn = findViewById(R.id.ssbutton);
        ssbtn.setOnClickListener(this);
    }
    
    public void onClick(View v)
    {
     switch(v.getId())
     {
     case R.id.ssbutton:
      if (check == true)
      {
       check = false;
      }else
      {
       check = true;
      }
      if (check == true)
      {
       v.setBackgroundResource(R.drawable.on);
      }
      if (check == false)
      {
       v.setBackgroundResource(R.drawable.off);
      }
     }
    }
}

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