Steps for creating a Calculator App

Steps for creating a Calculator App
Steps for creating a Calculator App

In this article, you are going to learn the method for creating a Calculator App in the Android Studio using a Kotlin class.

Pre-requisites:

Windows OS

  • Microsoft® Windows® 7/8/10 (64-bit)
  • 4 GB RAM minimum, 8 GB RAM recommended
  • 2 GB of available disk space minimum
  • 4 GB Recommended (500 MB for IDE + 1.5 GB for Android SDK and emulator system image)
  • 1280 x 800 minimum screen resolution

   Linux OS

  • GNOME or KDE desktop
  • Tested on gLinux based on Debian.
  • 64-bit distribution capable of running 32-bit applications
  • GNU C Library (glibc) 2.19 or later
  • 4 GB RAM minimum, 8 GB RAM recommended
  • 2 GB of available disk space minimum,
  • 4 GB Recommended (500 MB for IDE + 1.5 GB for Android SDK and emulator system image)
  • 1280 x 800 minimum screen resolution

Mac OS

  • Mac® OS X® 10.10 (Yosemite) or higher, up to 10.14 (macOS Mojave)
  • 4 GB RAM minimum, 8 GB RAM recommended
  • 2 GB of available disk space minimum,
  • 4 GB Recommended (500 MB for IDE + 1.5 GB for Android SDK and emulator system image)
  • 1280 x 800 minimum screen resolution

Learn one of the most powerful and portable programming languages C++ and become eligible to apply for the positions at Google, Microsoft, Facebook, Amazon etc.

Creating a new Android Project:

Step One: Open the Android Studio and select create a new project option. The following “Select a Project Template” dialogue appears.

Image Source: Screenshot from Android Studio

Step Two: From the “Select a Project Template” dialogue, select the “Empty Activity” template and click on the Next button. We choose the empty activity template as for creating a calculator we don’t need to add any map, advertisement or login templates, so an empty activity is the most suitable for our requirements.

Step Three:

  • After successful completion of step two, the “Configure your project” dialogue appears.
  • Add the name of your project in the “Name” column.
  • Make sure that you select Kotlin from the Language drop-down menu. (In case you are creating the app in Java, you can move forward with Java)
  • Check that the location of the project is preferable for you as the project will be saved there only.
  • Click on the “Finish” button after making the required changes.
Image Source: Screenshot from Android Studio

Phase One: Design

Language used: Extensible Markup Language (XML) which is a markup language used for defining a set of rules for encoding documents in a format, that is both human-readable and machine-readable.

Components for UI designing:

  • Two Edit Text :
  • One for first input number.
  • Another for second input number.
  • Three Linear layouts :
  • One Linear Layout with vertical orientation.
  • Two Linear Layouts with horizontal orientation.
  • Four Buttons:
  • One for the addition operation.
  • One for subtraction operation.
  • One for multiplication operation.
  • One for division operation.
  • Text View:
  • For displaying the answer.
Image Source: Screenshot from Android Emulator After successfully running the App

EDIT TEXT:

You need to add the following attributes:

  • Id: To extract text from the edit text for performing calculations.
  • Input type: To restrict the input type to numbers only.
  • Width and height: For setting the dimensions.
  • Padding: To add a gap between the text entered and the edge.
  • Background: For customising the background colour and shape.
  • Hint: To prompt the user by giving a message, so that he/she knows that he/she has to enter the value here.
  • Margin Left and Top: To leave a margin in the left side of the screen and to create a gap between the UI components.

XML code of EditText for reference

<EditText
android:id = "@+id/number_1"
android:inputType = "number"
android:paddingLeft = "30dp"
android:layout_width = "300dp"
android:layout_height = "50dp"
android:background = "@drawable/blue_round"
android:layout_marginLeft="50dp"
android:layout_marginTop = "50dp"
android:hint = "Enter the first number"
android:text = ""
/>

Buttons : Creating a nested Linear Layout for the arrangement

To create the arrangement for the buttons you can use nesting of linear layouts and set their orientation as vertical or horizontal.

This can be done in two ways:

  1. Use a horizontal layout for plus and minus button.
  2. Use a horizontal layout for plus and minus button.
  3. Put the two horizontal layouts inside a vertical layout.
  • Use a vertical layout for plus and minus button.
  • Use a vertical layout for plus and minus button.
  • Put the two vertical layouts inside a horizontal layout.

TEXT VIEW: Steps for creating a customised background

  • Step One: Right-click on drawable and click on the NEW option from the drop-down menu. Select Drawable resource file from the drop-down menu.
Image Source: Screenshot from Android Studio
  • Step Two: Enter the desirable file name and click on Ok. In our case, we enter “ans”, as we are going to use this for our TextView.
Image Source: Screenshot from Android Studio
  • Step Three: In the “ans.xml” file add the attributes that you want to use for your background.
    • Shape: We have used rectangular for our project. You can also try oval, ring, and line shape.
    • Solid: Used for adding colour to the shape we have created.
    • Corners: Used for rounding the edges.
    • Stroke: It is used for setting the border width.
Image Source: Screenshot from Android Studio

This is the complete XML code for the above mentioned UI design; this code is written in activity_main.xml:

<EditText
android:id = "@+id/number_1"
android:inputType = "number"
android:paddingLeft = "30dp"
android:layout_width = "300dp"
android:layout_height = "50dp"
android:background = "@drawable/blue_round"
android:layout_marginLeft="50dp"
android:layout_marginTop = "50dp"
android:hint = "Enter the first number"
android:text = ""
/>
<EditText
    android:id = "@+id/number_2"
    android:layout_width = "300dp"
    android:layout_height = "50dp"
    android:layout_marginLeft = "50dp"
    android:layout_marginTop = "30dp"
    android:inputType = "number"
    android:background = "@drawable/blue_round"
    android:paddingLeft = "30dp"
    android:hint = "Enter the second number"
    android:text = "" />

<LinearLayout
    android:layout_width = "200dp"
    android:layout_height = "140dp"
    android:layout_marginLeft = "100dp"
    android:layout_marginTop = "50dp"
    android:orientation = "vertical">
    <LinearLayout
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:orientation = "horizontal">
        <Button
            android:id = "@+id/add"
            android:layout_width = "100dp"
            android:text = "+"
            android:textStyle = "bold"
            android:layout_gravity = "center"
            android:background = "#D7D8D8"
            android:layout_height = "40dp">
        </Button>
        <Button
            android:id = "@+id/sub"
            android:layout_width = "100dp"
            android:textStyle = "bold"
            android:layout_gravity = "center"
            android:background = "#B0EBF1"
            android:text = "-"
            android:layout_height = "40dp">
        </Button>
    </LinearLayout>
    <LinearLayout
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"

        android:orientation = "horizontal">
</LinearLayout>

<TextView
    android:id = "@+id/answer"
    android:layout_marginLeft = "50dp"
    android:layout_marginTop = "30dp"
    android:layout_width = "300dp"
    android:paddingLeft = "30dp"
    android:background = "@drawable/ans"
    android:layout_height = "50dp"
    android:text = "" />

Frequently asked questions on Android UI design:

  • What is the difference between TextView and EditText?

TextView is a UI component in the Android Studio that is used for displaying the text only, user cannot type in a TextView. As the name suggests, it is used for viewing the text only. It is widely used in displaying messages, answers or results.

EditText is a UI component in the Android Studio that is used for taking values from the user, the user is allowed to enter any value depending upon the input type of the EditText. It remains editable as long as the activity containing it is not destroyed. It is widely used in the login page and registration forms.

  • What is the difference between vertical orientation and horizontal orientation?

Vertical orientation is used when you want to place one UI component below the other .No matter how many components you put in the linear layout, it will be placed below the previous components as far as its height permits.

Whereas, Horizontal orientation is used when you want to place one UI component beside the other. No matter how many components you put in the linear layout, it will be placed after the previous components as far as its width permits.

You can create a combination of Linear Layouts by nesting one another to create any desired combination. For instance, the arrangement of buttons in the Calculator App.

  • What are the various input type for EditText available in Android Studio?

The various types of text input type are:

  • number – A numeric only field
  • phone – For entering a phone number
  • date   – For entering a date
  • time – For entering a time
  • textMultiLine – Allow multiple lines of text in the field
  • textUri – Text that will be used as a URI
  • textEmailAddress – Text that will be used as an e-mail address
  • textPersonName – Text that is the name of a person
  • textPassword – Text that is a password that should be obscured
  • textVisiblePassword – Text that is a password that is not obscured
  • What do you mean by wrap_content and match_parent attributes for height and width properties?

wrap_content means the height or the width of the UI component will expand or shrink according to its contents. As in, for a TextView with width set as wrap_content, if it is empty then its width will be zero, but if you write “mug” its width will increase and if you write “redmug”, its width will be twice as previous.

match_parent means that the height or width of the UI component will be as its parent. The parent is the UI component inside which our UI component with  match_parent is present, as in, for nested components, the outer one is referred to as the parent.

Phase Two: Kotlin class

In the MainActivity.kt class, we create the functions add, subtract, multiply and divide. Using the id assigned to the UI components in the XML code we refer to them, you can set OnClickListener to the respective buttons for invoking the functions. But before this we call the inputIsNotEmpty function, it is used for ensuring that the user has entered the first as well as the second number. After, the button is clicked; the answer is displayed in the TextView.

The complete MainActivity.kt  code for the calculator app:

package com.example.calculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.math.BigDecimal
import java.math.RoundingMode

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

    add.setOnClickListener()
    {
        add()
    }
    sub.setOnClickListener()
    {
        subtract()
    }
    mul.setOnClickListener()
    {
        multiply()
    }
    div.setOnClickListener()
    {
        divide()
    }

}



    fun add()
    {
        if (inputIsNotEmpty()) 
        {
            val input1 = number_1.text.toString().trim().toBigDecimal()
            val input2 = number_2.text.toString().trim().toBigDecimal()
            answer.text = input1.add(input2).toString()
        }

    }


    fun subtract() 
    {
        if (inputIsNotEmpty())
        {
            val input1 = number_1.text.toString().trim().toBigDecimal()
            val input2 = number_2.text.toString().trim().toBigDecimal()
            answer.text = input1.subtract(input2).toString()
        }

    }


    fun multiply() {
        if (inputIsNotEmpty()) {
            val input1 = number_1.text.toString().trim().toBigDecimal()
            val input2 = number_2.text.toString().trim().toBigDecimal()
            answer.text = input1.multiply(input2).toString()
        }

    }

    fun divide() 
    {
        if (inputIsNotEmpty()) 
        {
            val input1 = number_1.text.toString().trim().toBigDecimal()
            val input2 = number_2.text.toString().trim().toBigDecimal()
            if (input2.compareTo(BigDecimal.ZERO) == 0)
            {
                number_2.error = "Invalid Input"
            }

            answer.text = input1.divide(input2, 2,          RoundingMode.HALF_UP).toString()
        }

    }

    fun inputIsNotEmpty(): Boolean 
    {
        var b = true
        if (number_1.text.toString().trim().isEmpty())
        {
            number_1.error = "Required"
            b = false
        }
        if (number_2.text.toString().trim().isEmpty()) 
        {
            number_2.error = "Required"
            b = false
        }
        return b
    }

}

Frequently asked questions on Calculator Kotlin Class:

  • What is the use of trim() function?

The trim() function in Kotlin returns a string having the leading and trailing whitespace removed. This implies that if the user adds any white spaces in the input with the number, the whitespaces are dropped.

  • What is the use of toBigDecimal() function?

The toBigDecimal() returns the value of the entered string as a BigDecimal. The BigDecimal class implements immutable arbitrary-precision decimal numbers. The methods of the BigDecimal class provide operations for fixed and floating-point comparison, arithmetic, format conversions, and hashing.

  • What do the three parameters of the in-built divide function given below signify:

answer.text=input1.divide(input2,2,RoundingMode.HALF_UP).toString()?

There are three parameters:

  1. The divisor
  2. The number of decimal digits in the answer.
  3. It is used for giving the enum value. Here, we have used HALF_UP – It is a rounding mode where values are rounded towards the nearest neighbour.
  • Why do we use the following line of code?

if (input2.compareTo(BigDecimal.ZERO) == 0)

{

number_2.error = “Invalid Input”

}

As in the case of division, the divisor can’t be zero else the function will give divide by zero error. Therefore, before calling the function, we check that the number entered by the user is not zero. If it is zero then we display an alert message, “Invalid Input”.

  • Why do we use the following line of code:

  number_2.error = “Required”?

The inputIsNotEmpty() checks that the user has entered both numbers. In case, the user forgets to enter the second number, .error displays an alert message. As the functions called on clicking the buttons require two parameters, so before making the function calls, we make sure that two input numbers are entered by the user.

Image Source: Screenshot from Android Emulator displaying an error in case the user forgets to enter any value.

Try implementing the code yourself. The more you practise the more you grow. However, if you stumble across anything you can refer to my GitHub repository.

Conclusion

A calculator application is a simple and basic application that is beneficial for developers and designers keeping in mind mini-projects they can do to strengthen their concepts of app development. The development of the entire application is a two-step easy process.

As you read in the article, first you have to go through the designing phase which will define the ‘what’ of your application development. In this phase, you have to ensure you are developing your application keeping in mind the needs of the user.

In the coding phase, you need to utilise a fast and robust language like Kotlin to make your application come to life. Mini projects like these help you in adding more stars to your development skills and you should always be on the lookout for enhancing your already made projects and creating more and more technological solutions. 

Happy Learning!

By Vanshika Singolia