Most Android apps involve using buttons to direct actions within the activity. Think about the built in calculator application. It is essentially made up of just a bunch of buttons. They may not look like the standard, buttons, but it is possible to skin Android buttons to look however you want.
Screenshot of the Android calculator. |
Step 1. Create a new Android project
Start a new android project. Call the project "Button Tutorial" and set the package name to "example." Check the "Create Activity" checkbox in the wizard and set the activity name to "MainActivity" If you need help see this tutorial for more information on creating a "Hello World" project.
Step 2. Create a layout that includes a button
For a full tutorial on create layouts, click here for the android layout tutorial.
Open up the layout file main.xml. Make sure the following properties are set for the parent linear layout.
Layout height: fill_parent
Layout width: fill_parent
Orientation: vertical
If there isn't a TextView in the layout already, add one. Set the following properties.
Id: @+id/TextViewCount
Text: "Count"
Text Size: 40dip
Layout height: wrap_content
Layout width: fill_parent
Layout margin bottom: 10dip
Now, add a Button to the layout, and set the following properties.
Id: @+id/ButtonCount
Text: Count
Min width: 125dip
Layout height: wrap_content
Layout width: wrap_content
Layout gravity: center
Feel free to adjust the properties as you see fit. Listed below is a screenshot of the layout we have created.
Screenshot of the layout created. |
Make sure to save your layout after you have modified it. When you save the layout, the generated Java class, R, will be recreated to include the ids of any new elements you have added to the layout.
Step 3. Add a OnClick listener to the button
Now that we have created the layout, its time to edit the actual Java code that is the logic behind the program. Open up MainActivity. It is located under src->example->MainActivity.java in the project explorer.
Screenshot of the MainActivity generated code |
Let's examine the code that is already there.
MainActivity extends the Activity class. Activities are the main components of Android Applications. The onCreate method gets called when the parts of the activity need to get built. The first line calls the super constructor, and the second line sets the layout of the activity.
Now add a member variable that will keep track of the count. The complete code for the activity so far is listed below.
package com.dreamdom.tutorials.buttontutorial; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { // Private member field to keep track of the count private int mCount = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
About Android Resources
The Android Developer Tools make it really easy to reference the components inside of your resources folder. The ADT will automatically generate a Java file, R, that contains unique integer ids for all your resources. These generated IDs can then be used in your Java code to reference the resources.
Do not modify the file R.java!
R.java is located inside "gen" folder for generated java files. You should never be editing generated files because you will likely
- Cause a problem
- Have your changes overwritten almost immediately
- Give yourself lots of headaches
Step 4. Obtaining references to the views
Now we want to obtain references to the views we created in the layout. We need these references in the Java file so that we can program the logic behind how they operate. Add the following code just below the setContentView... line
final TextView countTextView = (TextView) findViewById(R.id.TextViewCount); final Button countButton = (Button) findViewById(R.id.ButtonCount);
You will need to add the following lines at the top of your project.
import android.widget.TextView; import android.widget.Button;
If you are still getting errors as part of "R.id...." make sure that you have saved the layout after modifying it.
Now that we have references to these views we can modify them in all sorts of ways through the Java code. Most of the properties we've set in the layout editor can also be set by using member functions for the views.
Step 5. Add a onClickListener to the Count Button
Now that we have a reference to the count button, we want to add a listener that handles when the count button is clicked. An easy way to do this is to have an anonymous class implement the View.OnClick interface. The Code listed below demonstrates this.
countButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { } });
Make sure to add the following code to the top of the file.
import android.view.View; import android.view.OnClickListener
Step 6. Fill in the counting logic
Now we just need to fill in the logic that will increment the count, and update the value of the text view. Add the following code inside of the onClickListener that you just created.
mCount++; countTextView.setText("Count: " + mCount);
Step 7: The finished product
Finally, run your project and press the count button. You should see the count on the screen go up.
Screenshot of the finished app |
Full code for MainActivity.java
package com.dreamdom.tutorials.buttontutorial; 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 MainActivity extends Activity { // Private member field to keep track of the count private int mCount = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView countTextView = (TextView) findViewById(R.id.TextViewCount); final Button countButton = (Button) findViewById(R.id.ButtonCount); countButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mCount++; countTextView.setText("Count: " + mCount); } }); } }
Full code for main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Count" android:id="@+id/TextViewCount" android:textSize="40dip" android:layout_marginBottom="10dip" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Count" android:id="@+id/ButtonCount" android:minWidth="125dip"></Button> </LinearLayout>
As always, please leave any questions you have in the comments area, and I will be glad to help!
------------------------------------------------------------
We create these tutorials in our free time. If you like what you see please consider buying us a cup of coffee so we can keep creating useful material. Click on the image below to make a donation via Paypal.
Thanks very much for this tutorial! It was just what I needed. Cheers
ReplyDeleteThanks brov. I've done it well . But if i wanna run count updating code from a separate function..I am trying but i can't . Can u help me
ReplyDeleteVery useful to understand the basics. Thx!
ReplyDeleteExactly what I was looking for, cheers!
ReplyDeleteThanks for this tutorial! Exactly what I was looking for, cheers!
ReplyDeletehello, I just read your post about:
ReplyDeleteandroid-button-tutorial
I need to count how many times the user clicks on a especific button in 24 hours, and then reset the counter. The user not always be in the app, So I figure i need to use a small data base to recover the counter every day.
What should I do?
thanks in advance…
It helped me a Lot. Thanks a ton man!
ReplyDelete