Thursday, August 4, 2011

Android Custom Button Tutorial

This is a tutorial on how to create a custom button that changes appearance when a user taps it.  This is a quick and simple way to give feedback to your users that they have tapped a button.  You will learn how to create a xml file for your button resources and incorporate that xml file into your layout.  No Java required!


Step 1: Start a new Android Project
Click File>New>Android Project.  In the Project Name: field enter Custom Button Project.  Select the latest API level you are comfortable with (API10 for me).  In the Package name: field enter com.androgue.custombutton.  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 tapped a button, you need to provide images for each of the two states.  For this example, I used these two buttons below.

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

Step 3: Create a Button.xml
Right click on the drawable folder and select New>Android XML File.  Enter button into the name field and click Finish.  Add the following code to the file after the standard xml line.


Step 4: Modify 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 5: Run your App
Your app is now complete.  Start your favorite emulator and run the app.

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

No comments:

Post a Comment