Android Calculator Example Source Code

This example will show you how to use the android.widget.TableLayout and android.widget.Button to implement an android calculator application. It is a regular calculator which can execute +,, *, and / operation.

1. Android Calculator Example Overview.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/czdyBls4xPw.

  1. This example uses a table layout to arrange the buttons in table rows.
  2. The calculated number, operator, and result will be displayed in an edit text box.
  3. To use it please follow the below steps.
  4. Click the number buttons to input the first number.
  5. Click an operator button.
  6. Click the number buttons to input the second number.
  7. Click the = button to get the result displayed in the top edit text box.

2. Android Calculator Example Source Code.

  1. The core source files are a main activity java file and a layout XML file.
  2. The main activity java class implements the View.OnClickListener interface to process the button click event.
  3. Below is the example android project source files list.
    D:\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\TRANSITIONANIMATIONINTERPOLATOR
    │  .gitignore
    │  build.gradle
    │  gradle.properties
    │  gradlew
    │  gradlew.bat
    │  settings.gradle
    │
    ├─.idea
    │      encodings.xml
    │      gradle.xml
    │      misc.xml
    │      modules.xml
    │      runConfigurations.xml
    │      vcs.xml
    │
    ├─app
    │  │  .gitignore
    │  │  build.gradle
    │  │  proguard-rules.pro
    │  │
    │  └─src
    │      ├─androidTest
    │      │  └─java
    │      │      └─com
    │      │          └─dev2qa
    │      │              └─transitionanimationinterpolator
    │      │                      ExampleInstrumentedTest.java
    │      │
    │      ├─main
    │      │  │  AndroidManifest.xml
    │      │  │
    │      │  ├─java
    │      │  │  └─com
    │      │  │      └─dev2qa
    │      │  │          └─transitionanimationinterpolator
    │      │  │                  MainActivity.java
    │      │  │
    │      │  └─res
    │      │      ├─drawable
    │      │      │      ic_launcher_background.xml
    │      │      │
    │      │      ├─drawable-v24
    │      │      │      ic_launcher_foreground.xml
    │      │      │
    │      │      ├─layout
    │      │      │      activity_main.xml

2.1 Main Activity Java File.

  1. MainActivity.java
    package com.dev2qa.calculatorexample;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.WindowManager;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TableLayout;
    import android.widget.TableRow;
    
    /* This class implement View.OnClickListener interface to handel button click event. */
    public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    
        // This tag is used in console log output.
        private static final String TAG_CALCULATOR = "CALCULATOR";
    
        // Used to show calculate number and operator.
        private EditText resultEditText = null;
    
        // Record the first number before operator.
        private double firstNumber = Double.MIN_VALUE;
    
        // Record the second number before = operator.
        private double secondNumber = Double.MIN_VALUE;
    
        // Record user clicked operator.
        private String operator = "";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            setTitle("dev2qa.com - Android Calculator Example.");
    
            // Get the edit text input box.
            resultEditText = (EditText)findViewById(R.id.result);
    
            // Get the root table layout object.
            TableLayout rootView = (TableLayout) findViewById(R.id.root_view);
    
            // Disable the soft keyboard of edittext input view component.
            this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    
            // Get table layout row count.
            int rowCount = rootView.getChildCount();
    
            // Loop the table row list.
            for(int i=0;i<rowCount;i++)
            {
                // Get each table row.
                View childView = rootView.getChildAt(i);
    
                if(childView instanceof TableRow) {
                    TableRow tableRow = (TableRow)childView;
    
                    // Get table row child view count.
                    int childCount = tableRow.getChildCount();
    
                    for(int j=0;j<childCount;j++) {
    
                        childView = tableRow.getChildAt(j);
    
                        // If the table row's child is a button then set the button to use this activity as onclick listener.
                        if (childView instanceof Button) {
                            childView.setOnClickListener(this);
                        }
                    }
                }
            }
        }
    
        /* This method is invoked when activity screen is clicked. */
        @Override
        public void onClick(View view) {
    
            // If the clicked view object is a button.
            if(view instanceof Button)
            {
                // Get the button text.
                Button button = (Button)view;
                String buttonValue = button.getText().toString();
    
                // Check whether the button's text is a number or not.
                int buttonNumber = isInteger(buttonValue);
    
                if(buttonNumber != -1)
                {
                    // Get current edit text box value.
                    String currentValue = resultEditText.getText().toString();
    
                    if(isInteger(currentValue) > -1)
                    {
                        // If current value is a number then append new number to the end.
                        currentValue += buttonValue;
                        resultEditText.setText(currentValue);
                    }else
                    {
                        // Append the button number to edit text box.
                        resultEditText.setText(buttonValue);
                    }
    
                }else
                {
                    // If the button is operator button.
                    if("+".equals(buttonValue) || "-".equals(buttonValue) || "*".equals(buttonValue) || "/".equals(buttonValue))
                    {
                        // Get current number.
                        String currentValue = resultEditText.getText().toString();
                        if(isInteger(currentValue) > -1)
                        {
                            // Save it's value in firstNumber if the value is a number.
                            firstNumber = Double.parseDouble(currentValue);
                        }else
                        {
                            // Reset firstNumber value.
                            firstNumber = Double.MIN_VALUE;
                        }
    
                        // Save the operator.
                        operator = buttonValue;
                        // Show operator in edit text box.
                        resultEditText.setText(buttonValue);
                    }else if("c".equals(buttonValue))
                    {
                        // If user click c button then reset all value.
                        firstNumber = Double.MIN_VALUE;
                        secondNumber = Double.MIN_VALUE;
                        // Display empty string in edit text box.
                        resultEditText.setText("");
                    }else if("=".equals(buttonValue))
                    {
                        // Get current number.
                        String currentValue = resultEditText.getText().toString();
                        if(isInteger(currentValue) > -1)
                        {
                            // Save it's value in secondNumber if the value is a number.
                            secondNumber = Double.parseDouble(currentValue);
                        }else
                        {
                            // Reset firstNumber value.
                            secondNumber = Double.MIN_VALUE;
                        }
    
                        // If the button is equal button.
                        if(firstNumber > Long.MIN_VALUE && secondNumber > Long.MIN_VALUE) {
    
                            double resultNumber = 0;
    
                            // Calculate the result number.
                            if ("+".equals(operator)) {
                                resultNumber = firstNumber + secondNumber;
                            }else if("-".equals(operator))
                            {
                                resultNumber = firstNumber - secondNumber;
                            }else if("*".equals(operator))
                            {
                                resultNumber = firstNumber * secondNumber;
                            }else if("/".equals(operator))
                            {
                                resultNumber = firstNumber / secondNumber;
                            }
    
                            // Show the result number.
                            resultEditText.setText(String.valueOf(resultNumber));
                            // Save the result number as second result number.
                            secondNumber = resultNumber;
                            // Reset first number.
                            firstNumber = Double.MIN_VALUE;
                        }
                    }
                }
    
            }
        }
    
        /* Check whether a string value is an integer or not. */
        private int isInteger(String value)
        {
            int ret = -1;
            try {
                ret = Integer.parseInt(value);
            }catch(NumberFormatException ex)
            {
                Log.e(TAG_CALCULATOR, ex.getMessage());
            }finally {
                return ret;
            }
        }
    }

2.2 Main Activity Layout Xml File.

  1. activity_main.xml
    <TableLayout
        android:id="@+id/root_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="20dp"
        android:gravity="center_horizontal">
    
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <EditText
                android:id="@+id/result"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_span="4"
                android:gravity="end"
                android:editable="false"
                android:cursorVisible="false"
                android:ems="10"
                android:inputType="textPersonName"
                android:text=""
                android:textSize="50dp"/>
        </TableRow>
    
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
    
            <Button
                android:id="@+id/button_7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="7"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="8"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_9"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="9"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_plus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="+"
                android:textSize="20dp"/>
        </TableRow>
    
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
    
            <Button
                android:id="@+id/button_4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="4"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="5"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="6"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_minus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="-"
                android:textSize="20dp"/>
        </TableRow>
    
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
    
            <Button
                android:id="@+id/button_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="2"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="3"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_multiple"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="*"
                android:textSize="20dp"/>
        </TableRow>
    
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
    
            <Button
                android:id="@+id/button_0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="0"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_c"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="c"
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_equal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="="
                android:textSize="20dp"/>
    
            <Button
                android:id="@+id/button_divide"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="/"
                android:textSize="20dp"/>
        </TableRow>
    </TableLayout>

1 thought on “Android Calculator Example Source Code”

  1. this is very interesting , i want to know more about coding if you have any coding books or references please contact us

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.