In my first android app development post, I showed how you could easily create a simple to do list application from scratch. In this post however, we are going deeper or one step further by creating a Counter App that will change a value as well as the background color depending on which button is clicked. If you asking yourself of a use case, I am thinking of a scenario where you are playing family games and you want to keep score count. You can reset to zero when you are starting over. Pretty fun right? Let us look at the final product before writing some code:

Unlike my first post, this will not show you how to setup the development environment for android applications. If you need to do so, please read through the setup guide here and then come back for another exciting learning experience.

Counter App Definition

This app is relatively simple but not as simple as the todolist we created earlier. We will be using a few more things that might be new to you. Here are some of the things we will use in our development.

Instead of hard-coding strings, we will use values and resources that we will set inside the strings.xml file which resides in the values folder.

The main activity that we will define will implement an interface. In our previous tutorial, we used the OnKeyListener inside a method. We are not going to do that here because we want to make things easier to understand and stick to good coding styles.

inside a method. We are not going to do that here because we want to make things easier to understand and stick to good coding styles. There will be three buttons. Each of which will be listening for clicks. If one is clicked, we do something after knowing which one was clicked. The first button will add 1 to the counter, the second will subtract 1 and the third one will reset everything to 0.

If one is clicked, we do something after knowing which one was clicked. The first button will add 1 to the counter, the second will subtract 1 and the third one will reset everything to 0. There will be a few fancy things we will add: every time you click the reset button, the score background will change color. Likewise, when you click add or subtract, the score background will change as well. Styles, anyone?

button, the background will change color. Likewise, when you click add or subtract, the score background will change as well. Styles, anyone? The layout will include three components: TextView, EditText and Button. That is all.

I know you are probably thinking, show me the code. It is okay, but I think it is also good to understand the structure of the app before doing anything else.

Files that we will use

MainActivity.java main.xml strings.xml

Note: There are several folders that get created when you create a project using the Android tools on Eclipse. In those folders are files that you can use to add resources.Some, you don’t need to touch like R.java which is automatically generated for you. There is also the AndroidManifest.xml which we will talk about in the future tutorials. You are free to look inside those files but since we are not dealing with them directly in this post, I am not going to talk much about them.

Create Counter App project

Like we did in my first example, from within Eclipse IDE, let us go to File -> New ->Android Application Project. Fill in the details of your project and application. When you are done, you should have your project ready to go.

The easiest way to define the layout of your application is using the main.xml file that opens when your project is created. Yours might have a different name. While that file is open, you will see a Graphical Layout tab on the bottom of that file. To its right, you will see main.xml or whatever you named it. Here is a snapshot if you don’t mind:

As you can see, instead of typing all the xml inside main.xml file, you can simply drag and drop whatever components you want your app to show; like input areas, buttons, forms and many more. Doing that will save you a lot of time. Since we already have a TextView showing “Hello World”, we don’t need to drag a new one, we will instead edit the value and the name as well inside strings.xml file.

Drag and drop EditText – resize it as it pleases.

Drag and drop your first button.

Drag and drop your second button.

Drag and finally drop your third button.

Remember, what you see after dragging and dropping the components to your view is how your final app will look like. If you look inside your main.xml file, you will notice that EditText and three Buttons have been added and even positioned for you. Cool huh?

Using strings.xml file

I mentioned earlier that it is good to avoid hard-coding values in your app. Maybe your app needs to show different values for different countries or languages and that is why we use the res/values/strings.xml file. The Resource window looks like this:

We need to create four string names and values: Click Add, select string and add these:

name = intro, value = Score

name = addone, value = +1

name = subtractone, value = -1

name = reset, value = RESET SCORE

Type them without quotes. I am saying this because some people might have the idea of a string having double quotes around them. After creating these strings, we can now use them in our main.xml file:

main.xml

[xml]









[/xml]

First, we have our TextView where we use an id ‘myTextTitle’. As you can see, the last android:text has a value “@string/intro” – we just created that inside string.xml remember? The same applies to the three remaining buttons.

Note: Remember to Capitalize EditText, TextView and Button in your code – this syntax highlighter doesn’t do it as I would like it to. If you know a better highlighter for WordPress, please tell me.

We will need those ids to reference the components inside the java code that we will write next.

MainActivity.java

[java]

package com.simpledev.counterapp;

import android.os.Bundle;

import android.util.TypedValue;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.app.Activity;

import android.graphics.Color;

public class MainActivity extends Activity implements OnClickListener {

Button btn1;

Button btn2;

Button btn3;

TextView textTitle;

EditText scoreText;

int counter = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

btn1 = (Button)findViewById(R.id.addButton);

btn2 = (Button)findViewById(R.id.subtractButton);

btn3 = (Button)findViewById(R.id.resetButton);

scoreText = (EditText)findViewById(R.id.editText);

textTitle = (TextView)findViewById(R.id.myTextTitle);

//—set on click listeners on the buttons—–

btn1.setOnClickListener(this);

btn2.setOnClickListener(this);

btn3.setOnClickListener(this);

// change font size of the text

textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);

}

@Override

public void onClick(View v) {

if (v == btn1){

counter++;

scoreText.setText(Integer.toString(counter));

scoreText.setBackgroundColor(Color.CYAN);

}

if (v == btn2){

counter–;

scoreText.setText(Integer.toString(counter));

scoreText.setBackgroundColor(Color.GREEN);

}

if (v == btn3){

counter = 0;

scoreText.setText(Integer.toString(counter));

scoreText.setBackgroundColor(Color.RED);

}

}

}

[/java]

Code Breakdown

While defining our MainActivity.java class, we tell it to implement the OnClickListener interface which means we will have to use the onClick method . Eclipse is really cool, you only need to hover over MainActivity and double click it and a method is created for you. Repeat this procedure to import the necessary packages.

which means we will have to use the method . Eclipse is really cool, you only need to hover over MainActivity and double click it and a method is created for you. Repeat this procedure to import the necessary packages. Immediately after that, we define our objects. EditText, Button, TextView and a counter variable which we set to zero. At this point, we just define them and leave them for later use.

From within onCreate method, we finally assign values to our TextView, Buttons and EditText references. We are using the ids we assigned inside main.xml for each one of them. You can always switch between the java code and the xml file to make sure you don’t make errors or name mismatches.

We then set the OnClickListener on our buttons passing in the (this) keyword – the context. Remember we are doing all these inside MainActivity class.

I realized the Score text was too small and I therefore increased the size to 24. Pretty straight-forward I think.

Finally, we define what we want to do every time a particular button is clicked. Using *if* statements, we see if View v is equals to button 1, 2 or 3. Once that is clear, we either increment, decrease or reset the counter. Again, I added some cheap styles – changing background colors depending on which button was clicked.

That, is all you needed for this application to work.

If you have any questions, please let me know. I will truly appreciate you sharing this post with your friends online. Have comments? I would love to hear from you. Thank you for learning with me.