Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Android Calculator Tutorial: Creating an Calculator App

In this tutorial I will show you how to create a calculator application in Android. It will have the following functionality: division, multiplication, subtraction, addition, decimal place, decimal calculations, backspace button and a cancel but

Introduction

While creating the tutorial I assumed that the viewer already has a good understand of the Java language. This tutorial is a great way to see how a simple application can be so useful.

Here’s the code for the xmls and java files:

Listing 1: home.xml

<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/calc"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="25dp"
android:text="@string/app_name"
android:textColor="#000"
android:textSize="25sp"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_marginLeft="70dp"
android:layout_weight="0.04"
android:text="@string/app_name_slogan"
android:textColor="#000"
android:textSize="15sp"/>

</LinearLayout>

Stays the same. Note you must have an image for your splashcreen/homescreen. You can put one in your res folder under drawable-mdpi or if you are totally stuck just stick in android:background="@drawable/ic_launcher" as there is an image in there already.

Listing 2: Home.xml

packagecom.example.calc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

publicclass Home extends Activity{

@Override
protectedvoid onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        Thread th = new Thread(){
publicvoid run(){
try{
sleep(1000);
                }
catch(Exception e){
                    e.printStackTrace();
                }
finally{
                    onPause();
                    startActivity(new Intent("com.example.calc.CALC"));
                }
            }
        };
        th.start();
    }
@Override
publicvoid onPause(){
super.onPause();
        finish();
    }

}  

Stays the same just be wary of package names here as this one may differ to yours now if you used the previous code.

Note: My calc.xml is named activity_main.xml in this new example but I’ll point that out to you later, it doesn’t make much difference once you are aware of it.

Listing 3: calc.xml

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Home"
android:background="#fff">

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/disp"
android:id="@+id/display"
android:hint="@string/dispHint"/>
<LinearLayoutandroid:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:paddingTop="20dp">
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/seven"
android:text="@string/seven"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/eight"
android:text="@string/eight"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/nine"
android:text="@string/nine"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/div"
android:text="@string/div"
/>
</LinearLayout>
<LinearLayoutandroid:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:paddingTop="20dp">
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/four"
android:text="@string/four"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/five"
android:text="@string/five"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/six"
android:text="@string/six"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/mul"
android:text="@string/mul"
/>
</LinearLayout>
<LinearLayoutandroid:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:paddingTop="20dp">
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/one"
android:text="@string/one"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/two"
android:text="@string/two"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/three"
android:text="@string/three"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/sub"
android:text="@string/sub"
/>
</LinearLayout>
<LinearLayoutandroid:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:paddingTop="20dp">
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/cancel"
android:text="@string/cancel"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/zero"
android:text="@string/zero"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/equal"
android:text="@string/equal"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/add"
android:text="@string/add"
/>
</LinearLayout>

<LinearLayoutandroid:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:paddingTop="20dp">
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/backspace"
android:text="@string/backspace"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/dot"
android:text="@string/dot"
/>

<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/blank"
android:text="@string/blank"
/>
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id="@+id/blank2"
android:text="@string/blank2"
/>

</LinearLayout>
</LinearLayout>

Basically here we create a new row of buttons, backspace (bsp), dot (.) and 2 blank un-functioning buttons as seen from the highlighted code above and the graphic below.

Graphic Layout looks like this once all code is added:

Calculator design

Figure 1: Calculator design

Listing 4: Strings.xml

<?xmlversion="1.0"encoding="utf-8"?>
<resources>

<stringname="app_name">Quick Calc</string>
<stringname="action_settings">Settings</string>
<stringname="hello_world">Hello world!</string>

<stringname="zero">0</string>
<stringname="one">1</string>
<stringname="two">2</string>
<stringname="three">3</string>
<stringname="four">4</string>
<stringname="five">5</string>
<stringname="six">6</string>
<stringname="seven">7</string>
<stringname="eight">8</string>
<stringname="nine">9</string>

<stringname="mul">*</string>
<stringname="sub">-</string>
<stringname="cancel">C</string>
<stringname="add">+</string>
<stringname="equal">=</string>
<stringname="div">/</string>

<stringname="disp"></string>
<stringname="dispHint"></string>

<stringname="app_name_slogan">calculate anything easily and quickly</string>

<stringname="backspace">bsp</string>
<stringname="dot">.</string>
<stringname="blank"></string>
<stringname="blank2"></string>

</resources>

From the above code we can see the additions of backspace, dot, blank and blank2.

Listing 5: Calc.java

import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
importandroid.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

publicclass Calc extends Activity implements View.OnClickListener{

    Button one, two, three, four, five, six, seven, eight, nine, zero, add, sub, mul, div, cancel, equal, backspace, dot;
    EditText disp;
intop1;
intop2;
doubleop3;
doubleop4;
    String optr;

@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);  //yours will be calc.xml here

one = (Button) findViewById(R.id.one);
two = (Button) findViewById(R.id.two);
three = (Button) findViewById(R.id.three);
four = (Button) findViewById(R.id.four);
five = (Button) findViewById(R.id.five);
six = (Button) findViewById(R.id.six);
seven = (Button) findViewById(R.id.seven);
eight = (Button) findViewById(R.id.eight);
nine = (Button) findViewById(R.id.nine);
zero = (Button) findViewById(R.id.zero);
add = (Button) findViewById(R.id.add);
sub = (Button) findViewById(R.id.sub);
mul = (Button) findViewById(R.id.mul);
div = (Button) findViewById(R.id.div);
cancel = (Button) findViewById(R.id.cancel);
equal = (Button) findViewById(R.id.equal);
backspace = (Button) findViewById(R.id.backspace);
dot = (Button) findViewById(R.id.dot);

disp = (EditText) findViewById(R.id.display);

try{
one.setOnClickListener(this);

two.setOnClickListener(this);

three.setOnClickListener(this);

four.setOnClickListener(this);

five.setOnClickListener(this);

six.setOnClickListener(this);

seven.setOnClickListener(this);

eight.setOnClickListener(this);

nine.setOnClickListener(this);

zero.setOnClickListener(this);

cancel.setOnClickListener(this);

add.setOnClickListener(this);

sub.setOnClickListener(this);

mul.setOnClickListener(this);

div.setOnClickListener(this);

equal.setOnClickListener(this);

backspace.setOnClickListener(this);

dot.setOnClickListener(this);
        }
catch(Exception e){

        }
    }
publicvoid operation(){
/*if(optr.equals("+")){
            op2 = Integer.parseInt(disp.getText().toString());
            disp.setText("");
            op1 = op1 + op2;
            disp.setText("Result : " + Integer.toString(op1));
        }*/
	if(optr.equals("+")){
op4 = Double.parseDouble(disp.getText().toString());
disp.setText("");
op3 = op3 + op4;
disp.setText("Result : "+ Double.toString(op3));
	}
/* else if(optr.equals("-")){
            op2 = Integer.parseInt(disp.getText().toString());
            disp.setText("");
            op1 = op1 - op2;
            disp.setText("Result : " + Integer.toString(op1));
        }*/
elseif(optr.equals("-")){
	op4 = Double.parseDouble(disp.getText().toString());
disp.setText("");
op3 = op3 - op4;
disp.setText("Result : " + Double.toString(op3));
        }
/* else if(optr.equals("*")){
            op2 = Integer.parseInt(disp.getText().toString());
            disp.setText("");
            op1 = op1 * op2;
            disp.setText("Result : " + Integer.toString(op1));
        }*/
elseif(optr.equals("*")){
op4 = Double.parseDouble(disp.getText().toString());
disp.setText("");
op3 = op3 * op4;
disp.setText("Result : " + Double.toString(op3));
        }
	/*
        else if(optr.equals("/")){
            op2 = Integer.parseInt(disp.getText().toString());
            disp.setText("");
            op1 = op1 / op2;
            disp.setText("Result : " + Integer.toString(op1));
        }*/
elseif(optr.equals("/")){
	op4 = Double.parseDouble(disp.getText().toString());
disp.setText("");
op3 = op3 / op4;;
disp.setText("Result : " + Double.toString(op3));
        }
    }
	@Override
publicvoid onClick(View arg0) {
        Editable str =  disp.getText();
switch(arg0.getId()){
case R.id.one:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(one.getText());
disp.setText(str);
break;
case R.id.two:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(two.getText());
disp.setText(str);
break;
case R.id.three:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(three.getText());
disp.setText(str);
break;
case R.id.four:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(four.getText());
disp.setText(str);
break;
case R.id.five:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(five.getText());
disp.setText(str);
break;
case R.id.six:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(six.getText());
disp.setText(str);
break;
case R.id.seven:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(seven.getText());
disp.setText(str);
break;
case R.id.eight:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(eight.getText());
disp.setText(str);

break;
case R.id.nine:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(nine.getText());
disp.setText(str);

break;
case R.id.zero:
if(op2 != 0){
op2 = 0;
disp.setText("");
                }
                str = str.append(zero.getText());
disp.setText(str);

break;
case R.id.cancel:
op1 = 0;
op2 = 0;
op3 = 0;
op4 = 0;
disp.setText("");
//disp.setHint("Perform Operation :)"); (No need for)

break;
/*case R.id.add:
optr = "+";
                if(op1 == 0){
                    op1 = Integer.parseInt(disp.getText().toString());
                    disp.setText("");
                }
                else if(op2 != 0){
                    op2 = 0;
                    disp.setText("");
                }
                else{
                    op2 = Integer.parseInt(disp.getText().toString());
                    disp.setText("");
                    op1 = op1 + op2;
                    disp.setText("Result : " + Integer.toString(op1));
                }
            break;*/
case R.id.add:
optr = "+";
if(op3 == 0){
	op3 = Double.parseDouble(disp.getText().toString());
disp.setText("");
                }
elseif(op4 != 0){
op4 = 0;
disp.setText("");
                }
else{
op4 = Double.parseDouble(disp.getText().toString());
disp.setText("");
op3 = op3 + op4;
disp.setText("Result : "+ Double.toString(op3));
                }
break;
/*case R.id.sub:
optr = "-";
                if(op1 == 0){
                    op1 = Integer.parseInt(disp.getText().toString());
                    disp.setText("");
                }
                else if(op2 != 0){
                    op2 = 0;
                    disp.setText("");
                }
                else{
                    op2 = Integer.parseInt(disp.getText().toString());
                    disp.setText("");
                    op1 = op1 - op2;
                    disp.setText("Result : " + Integer.toString(op1));
                }
            break;*/
case R.id.sub:
optr = "-";
if(op3 == 0){
	op3 = Double.parseDouble(disp.getText().toString());
disp.setText("");
                }
elseif(op4 != 0){
op4 = 0;
disp.setText("");
                }
else{
op4 = Double.parseDouble(disp.getText().toString());
disp.setText("");
op3 = op3 - op4;
disp.setText("Result : " + Double.toString(op3));
                }
break;
case R.id.mul:
optr = "*";
if(op3 == 0){
	op3 = Double.parseDouble(disp.getText().toString());
disp.setText("");
                }
elseif(op4 != 0){
op4 = 0;
disp.setText("");
                }
else{
op4 = Double.parseDouble(disp.getText().toString());
disp.setText("");
op3 = op3 * op4;
disp.setText("Result : " + Double.toString(op3));
                }
/*
            case R.id.mul:
optr = "*";
                if(op1 == 0){
                    op1 = Integer.parseInt(disp.getText().toString());
                    disp.setText("");
                }
                else if(op2 != 0){
                    op2 = 0;
                    disp.setText("");
                }
                else{
                    op2 = Integer.parseInt(disp.getText().toString());
                    disp.setText("");
                    op1 = op1 * op2;
                    disp.setText("Result : " + Integer.toString(op1));
                }*/
break;
/*case R.id.div:
optr = "/";
                if(op1 == 0){
                    op1 = Integer.parseInt(disp.getText().toString());
                    disp.setText("");
                }
                else if(op2 != 0){
                    op2 = 0;
                    disp.setText("");
                }
                else{
                    op2 = Integer.parseInt(disp.getText().toString());
                    disp.setText("");
                    op1 = op1 / op2;
                    disp.setText("Result : " + Integer.toString(op1));
                }
            break;*/
case R.id.div:
optr = "/";
if(op3 == 0){
	op3 = Double.parseDouble(disp.getText().toString());
disp.setText("");
                }
elseif(op4 != 0){
op4 = 0;
disp.setText("");
                }
else{
	op4 = Double.parseDouble(disp.getText().toString());
disp.setText("");
op3 = op3 / op4;
disp.setText("Result : " + Double.toString(op3));
                }
break;
/*case R.id.equal:
                if(!optr.equals(null)){
                    if(op2 != 0){
                        if(optr.equals("+")){
                            disp.setText("");
                            //op1 = op1 + op2;
                            disp.setText("Result : " + Integer.toString(op1));
                        }
                        else if(optr.equals("-")){
                            disp.setText("");
                           // op1 = op1 - op2;
                            disp.setText("Result : " + Integer.toString(op1));
                        }
                        else if(optr.equals("*")){
                            disp.setText("");
                            //op1 = op1 * op2;
                            //disp.setText("Result : " + Integer.toString(op1));
                            disp.setText("Result : " + Double.toString(op1));
                        }
                        else if(optr.equals("/")){
                            disp.setText("");
                            //op1 = op1 / op2;
                            disp.setText("Result : " + Integer.toString(op1));
                        }
                    }
                    else{
                        operation();
                    }
                }
            break;*/
case R.id.equal:
if(!optr.equals(null)){
if(op4 != 0){
if(optr.equals("+")){
disp.setText("");
/*op1 = op1 + op2;*/
disp.setText("Result : " + Double.toString(op3));
                        }
elseif(optr.equals("-")){
disp.setText("");/*
                            op1 = op1 - op2;*/
disp.setText("Result : " + Double.toString(op3));
                        }
elseif(optr.equals("*")){
disp.setText("");/*
                            op1 = op1 * op2;*/
//disp.setText("Result : " + Integer.toString(op1));
disp.setText("Result : " + Double.toString(op3));
                        }
elseif(optr.equals("/")){
disp.setText("");/*
                            op1 = op1 / op2;*/
disp.setText("Result : " + Double.toString(op3));
                        }
                    }
else{
                        operation();
                    }
                }
break;
case R.id.dot:
if(op4 != 0){
op4 = 0;
disp.setText("");
                }
str = str.append(dot.getText());
disp.setText(str);

break;
case R.id.backspace:
if(op4 != 0){
op4 = 0;
disp.setText("");
                }
// Get edit text characters 
                String textInBox = disp.getText().toString(); 
if(textInBox.length() > 0)
                {
//Remove last character// 
                  String newText = textInBox.substring(0, textInBox.length()-1); 
// Update edit text 
disp.setText(newText); 
                }

break;

        }
    }
}

Okay, from the code above we have modified it so we can add extra functionality. See the highlighted text for reference and feel free to copy and paste it into your project. Not all changes are highlighted as they repeat themselves for different functionality in the code. We have declared a dot and backspace button, added their onclick listeners and added their functionality also.

With respect to the backspace button we used this code:

// Get edit text characters 
                String textInBox = disp.getText().toString(); 
if(textInBox.length() > 0)
                {
//Remove last character// 
                  String newText = textInBox.substring(0, textInBox.length()-1); 
// Update edit text 
disp.setText(newText); 
                }

It basically gets the edit texts characters, if it’s greater than 0 we create a new string called newText consisting of String textInBox’s characters minus 1 character and assigns it to the display.

Adding the dot is like adding the numbers to the display, it’s the same principle. It’s functionality though requires the working out of decimals in our calculations.

So now we also have to accommodate for decimal numbers as integers will not suffice here. We did this by declaring op3 and op4, both doubles and modifying the code accordingly when carrying out the operations.

You can see where I blanked out the old code and put in the new above.

Just note my package name may differ from yours, so you will more than likely need to change it where necessary.

Listing 6: AndroidManifest.xml

<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.calc"
android:versionCode="1"
android:versionName="1.0">

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.example.calc.Home"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>

<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="com.example.calc.Calc"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="com.example.calc.CALC"/>

<categoryandroid:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>

</manifest>

Conclusion

You should now have the extra functionality of a decimal point button and a backspace button with the relevant fixes. It will now divide, multiply, subtract and add decimal values and also output a decimal answer for you. I hope this updated code is useful to you and I hope you enjoyed this answer. Happy coding :)



Has designed and developed several android applications from scratch which are available on Google Play.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login