Hello there, this tutorial gives detailed information about how to create a simple android calculator app. This tutorial is for beginners who just started there android development journey. In this tutorial, we are covering topics such as how to create layouts, how to add buttons and much more.

This tutorial assumes that you are having some little experience in Android development and Android studio. If you are new to Android development please check out our Android development guide for beginners.

Now we are going to develop a calculator similar to the app shown in the following image.

SImple calculator app

Calculator app

The source code about which I am going discuss is available on GitHub for reuse and modification as much as you like. Here is the link.

Creating a project

To start with this project, the first thing you need to do is to create a new project. You can do it by clicking on

“File-> New -> New Project”  .

Creating new project

Creating new project

Give the name to your project as “calculator”. After creation of new project gradle will synchronize the dependencies in build.gradle file and download the specified version of files. Following image shows the project files structure of our calculator project.

calculator project structure

calculator project structure

In this project, you are mostly going to interact with following files, layout XML files specified in layout folder for UI designing and java files for writing the logic of your operations. While creating the project, choose empty activity template.

You might be wondering what is splash screen here?

A splash screen is the initial welcome screen which shows the name of the app and some icons with extra information.

Our splash screen will look like as shown in the following image.

splash screen

splash screen

 

Designing the splash screen layout

Add a new activity to our project named as SplashActivity.

Modify the AndroidManifest.xml file as shown in the following code.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderfolk.calculator">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">

        </activity>
        <activity android:name=".SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

In above file, we modified the intent filter of our Android app. The SplashActivity is defined as a launcher activity here.

Now let’s move to the designing of splash layout. To design the layout we are going to use Linear layout because of its simplicity.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".SplashActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="152dp"
        android:layout_height="144dp"
        android:src="?android:attr/textSelectHandleLeft"
        tools:layout_editor_absoluteX="116dp"
        tools:layout_editor_absoluteY="121dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CALCULATOR"
        android:textColor="@color/colorAccent"
        android:textSize="30sp"
        android:textStyle="bold"
        android:typeface="monospace"
        tools:layout_editor_absoluteX="95dp"
        tools:layout_editor_absoluteY="265dp" />
</LinearLayout>

In above layout, ImageView is used to show the image and TextView for our calculator name.

Designing calculator layout

Following code refers to the activity_main.xml file. This will layout code to design our calculator UI

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingVertical="30dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="?android:attr/textSelectHandleLeft" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25dp"
            android:text="Calculator" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="100dp">

        <EditText
            android:id="@+id/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:ems="10"
            android:hint="@string/value_1"
            android:inputType="numberDecimal"
            app:layout_constraintBottom_toTopOf="@+id/editText2"
            tools:layout_editor_absoluteX="84dp" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/value_2"
            android:inputType="numberDecimal"
            tools:layout_editor_absoluteX="84dp"
            tools:layout_editor_absoluteY="121dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingVertical="50dp">

        <Button
            android:id="@+id/div"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_blue_light"
            android:text="/" />

        <Button
            android:id="@+id/mul"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="*"
            android:background="@android:color/holo_blue_light"

            />

        <Button
            android:id="@+id/sub"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="-"
            android:background="@android:color/holo_blue_light"

            />

        <Button
            android:id="@+id/add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+"
            android:background="@android:color/holo_blue_light"
            />

    </LinearLayout>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:fontFamily="monospace"
        android:text="Answer will be shown here"
        android:textSize="20dp"
        android:textStyle="bold" />


</LinearLayout>

For designing the calculator layout you are again going to use LinearLayout. Linear layout container follows two orientation for its widgets i.e Horizontal or Vertical.

Code for Splash screen activity

Following code is used to develop our splash screen logic. In below-mentioned code, Handler object is used to wait for the event to be executed. Handler is specifically used to execute some event after some time period. It is used to execute events in future.

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SplashActivity extends Activity {
    private static boolean splashLoaded = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!splashLoaded) {
            setContentView(R.layout.activity_splash);
            int secondsDelayed = 1;
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }
            }, secondsDelayed * 500);

            splashLoaded = true;
        }
        else {
            Intent goToMainActivity = new Intent(SplashActivity.this, MainActivity.class);
            goToMainActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(goToMainActivity);
            finish();
        }
    }
}

In above code, when the specific timer is out then MainActivity get executed.

We use Intents to send some data to another activity from one activity and to launch another activity from the running activity.

Code for Calculator

Following code is used to develop the logic for our main calculator.

In our calculator UI, we are having two EditText component and four buttons.

Refer the following code before we discuss ahead.

public class MainActivity extends AppCompatActivity {
    Button add, sub, mul, div = null;
    TextView answer = null;
    EditText value1, value2 = null;
.....

}

In the MainActivity.java we created Instance of Buttons, Textview, and EditText. To interact with the UI components these objects created.

protected void onCreate(Bundle savedInstanceState) {
        .......

        add = (Button) findViewById(R.id.add);
        sub = (Button) findViewById(R.id.sub);
        mul = (Button) findViewById(R.id.mul);
        div = (Button) findViewById(R.id.div);
        answer = (TextView) findViewById(R.id.textView);
        value1 = (EditText) findViewById(R.id.editText);
        value2 = (EditText) findViewById(R.id.editText2);
......
}

As shown in above code, we are initializing our object with its corresponding view using findViewById() method. We need to cast our object because findViewById() methods return an object of type View and we need the object of type Button, TextView and EditText.

Now we’ll add OnClickListener on our Buttons to attach the click event. Whenever the user clicks on Button it has to perform some intended operations.

For example in our activity add button will perform the action of the addition of two numbers which are in the EditText.

To fetch that values and perform actions using the following code.

 

add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidekeyboard();              //to hide keyboard after clicking on button
                if (value1.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else if (value2.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else {
                    double number1 = Double.parseDouble(value1.getText().toString());
                    double number2 = Double.parseDouble(value2.getText().toString());
                    double number3 = number1 + number2;
                    answer.setTextColor(Color.BLACK);
                    answer.setText(String.valueOf(number3));
                    add.setBackgroundColor(Color.MAGENTA);
                    sub.setBackgroundColor(Color.rgb(239,240,241));
                    mul.setBackgroundColor(Color.rgb(239,240,241));
                    div.setBackgroundColor(Color.rgb(239,240,241));
                }
            }
        });

 

Look at the code, here we are getting values from the EditText in the form of String. We are converting these String values into double datatype. For this, we parse the value using Double.parseDouble() method. We are storing the answer in the variable number3.

We are applying the same kind of logic for division, multiplication and subtraction.

You can refer following the full version of the code in MainActivity.java. Copy the following code in your MainActivity.java file

 

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    Button add, sub, mul, div = null;
    TextView answer = null;
    EditText value1, value2 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getSupportActionBar().hide();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        add = (Button) findViewById(R.id.add);
        sub = (Button) findViewById(R.id.sub);
        mul = (Button) findViewById(R.id.mul);
        div = (Button) findViewById(R.id.div);
        answer = (TextView) findViewById(R.id.textView);
        value1 = (EditText) findViewById(R.id.editText);
        value2 = (EditText) findViewById(R.id.editText2);
        value1.setText("");
        value2.setText("");
        findViewById(R.id.mainLayout).setBackgroundColor(Color.WHITE);
        add.setBackgroundColor(Color.rgb(239,240,241));
        sub.setBackgroundColor(Color.rgb(239,240,241));
        mul.setBackgroundColor(Color.rgb(239,240,241));
        div.setBackgroundColor(Color.rgb(239,240,241));
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidekeyboard();              //to hide keyboard after clicking on button
                if (value1.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else if (value2.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else {
                    double number1 = Double.parseDouble(value1.getText().toString());
                    double number2 = Double.parseDouble(value2.getText().toString());
                    double number3 = number1 + number2;
                    answer.setTextColor(Color.BLACK);
                    answer.setText(String.valueOf(number3));
                    add.setBackgroundColor(Color.MAGENTA);
                    sub.setBackgroundColor(Color.rgb(239,240,241));
                    mul.setBackgroundColor(Color.rgb(239,240,241));
                    div.setBackgroundColor(Color.rgb(239,240,241));
                }
            }
        });

        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidekeyboard();
                if (value1.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else if (value2.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else {
                    double number1 = Double.parseDouble(value1.getText().toString());
                    double number2 = Double.parseDouble(value2.getText().toString());
                    double number3 = number1 - number2;
                    answer.setText(String.valueOf(number3));
                    answer.setTextColor(Color.BLACK);
                    add.setBackgroundColor(Color.rgb(239,240,241));
                    sub.setBackgroundColor(Color.MAGENTA);
                    mul.setBackgroundColor(Color.rgb(239,240,241));
                    div.setBackgroundColor(Color.rgb(239,240,241));
                }
            }
        });

        mul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidekeyboard();
                if (value1.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else if (value2.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else {
                    double number1 = Double.parseDouble(value1.getText().toString());
                    double number2 = Double.parseDouble(value2.getText().toString());
                    double number3 = number1 * number2;
                    answer.setText(String.valueOf(number3));
                    answer.setTextColor(Color.BLACK);
                    add.setBackgroundColor(Color.rgb(239,240,241));
                    sub.setBackgroundColor(Color.rgb(239,240,241));
                    mul.setBackgroundColor(Color.MAGENTA);
                    div.setBackgroundColor(Color.rgb(239,240,241));
                }

            }
        });

        div.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidekeyboard();
                if (value1.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else if (value2.getText().toString().equals("")) {
                    answer.setText(R.string.warning);
                    answer.setTextColor(Color.RED);
                } else {
                    double number3 = 0;
                    try {
                        double number1 = Double.parseDouble(value1.getText().toString());
                        double number2 = Double.parseDouble(value2.getText().toString());
                        number3 = number1 / number2;
                        answer.setText(String.valueOf(number3));
                        answer.setTextColor(Color.BLACK);
                        add.setBackgroundColor(Color.rgb(239,240,241));
                        sub.setBackgroundColor(Color.rgb(239,240,241));
                        mul.setBackgroundColor(Color.rgb(239,240,241));
                        div.setBackgroundColor(Color.MAGENTA);
                    } catch (ArithmeticException e) {
                        e.printStackTrace();
                        answer.setTextColor(Color.RED);
                        answer.setText("You should not divide any number by zero");
                    }
                    answer.setText(String.valueOf(number3));
                }
            }
        });
    }

    private void hidekeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

Now build the above code and execute. The whole project is available on GitHub.

Enjoy, keep learning, All the best 🙂

 


Leave a Reply

Your email address will not be published. Required fields are marked *