How To Make A Simple Calculator Using Kotlin In Android

Introduction

In this article, we are going to learn how to make a simple calculator using kotlin in android. We are going to perform some basic operations such as addition, subtraction, multiplication, division, etc. 

Let's start with implementation,

Step 1

Create a new project and select an empty activity.

 

Select kotlin language and click on the finish button.

Step 2

Go to activity_main.xml and add the following code. 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="280dp"
        android:orientation="vertical">

        <com.google.android.material.card.MaterialCardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"
            android:elevation="20dp"
            app:strokeColor="@color/teal_700"
            app:strokeWidth="1dp">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/input1"
                android:inputType="number"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Enter 1st Number"
                android:textSize="20dp" />

        </com.google.android.material.card.MaterialCardView>

        <com.google.android.material.card.MaterialCardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:elevation="20dp"
            app:strokeColor="@color/teal_700"
            app:strokeWidth="1dp">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/input2"
                android:inputType="number"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Enter 2nd Number"
                android:textSize="20dp" />

        </com.google.android.material.card.MaterialCardView>

        <com.google.android.material.card.MaterialCardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="12dp"
            android:layout_marginRight="15dp"
            android:elevation="20dp"
            app:strokeColor="@color/teal_700"
            app:strokeWidth="1dp">

            <TextView
                android:id="@+id/result"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:gravity="center"
                android:text="Result"
                android:textSize="20sp"/>

        </com.google.android.material.card.MaterialCardView>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <com.google.android.material.button.MaterialButton
                android:id="@+id/plus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dp"
                android:layout_marginTop="15dp"
                android:backgroundTint="@color/teal_700"
                android:text="+"
                android:textSize="20dp"
                app:strokeColor="@color/white"
                app:strokeWidth="2dp" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/minus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="15dp"
                android:backgroundTint="@color/teal_700"
                android:text="-"
                android:textSize="20dp"
                app:strokeColor="@color/white"
                app:strokeWidth="2dp" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/multiply"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="15dp"
                android:backgroundTint="@color/teal_700"
                android:text="*"
                android:textSize="20dp"
                app:strokeColor="@color/white"
                app:strokeWidth="2dp" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/divide"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="15dp"
                android:layout_marginRight="15dp"
                android:backgroundTint="@color/teal_700"
                android:text="/"
                android:textSize="20dp"
                app:strokeColor="@color/white"
                app:strokeWidth="2dp" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

Explanation

Here, I am taking a relative layout and inside this layout, we have a linear layout having an orientation vertical. I am taking two TextInputEditText and one TextView inside this linear layout. I have used MaterialCardView to design the TextInputEditText and TextView. Now I am taking another linear layout having an orientation horizontal. We have to take four material buttons for performing addition, subtraction, multiplication, and division operations inside this inner linear layout.

activity_main.xml layout 

  

Step 3

Go to MainActivity.kt and add the following code

MainActivity.kt

package com.example.simplecalculator

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
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)
        supportActionBar?.setBackgroundDrawable(
            ColorDrawable(Color.parseColor("#FF018786")))

        plus.setOnClickListener {
            add()
        }

        minus.setOnClickListener {
            subtract()
        }

        multiply.setOnClickListener {
            multiply()
        }

        divide.setOnClickListener {
            divide()
        }

    }


    fun  inputIsNotEmpty():Boolean{
        var b=true;
        if(input1.text.toString().trim().isEmpty()){
            input1.error="Required"
            input1.requestFocus()
            b=false;
        }
        if(input2.text.toString().trim().isEmpty()){
            input2.error="Required"
            input2.requestFocus()
            b=false;
        }
        return  b;
    }

    fun add(){
        if(inputIsNotEmpty()){
            var inputdata1=input1.text.toString().trim().toBigDecimal()
            var inputdata2=input2.text.toString().trim().toBigDecimal()
            result.text=inputdata1.add(inputdata2).toString()
        }
    }

    fun subtract(){
        if(inputIsNotEmpty()){
            var inputdata1=input1.text.toString().trim().toBigDecimal()
            var inputdata2=input2.text.toString().trim().toBigDecimal()
            result.text=inputdata1.subtract(inputdata2).toString();
        }
    }

    fun multiply(){
        if(inputIsNotEmpty()){
            var inputdata1=input1.text.toString().trim().toBigDecimal()
            var inputdata2=input2.text.toString().trim().toBigDecimal()
            result.text=inputdata1.multiply(inputdata2).toString()
        }
    }


    fun divide(){
        if(inputIsNotEmpty()){
            var inputdata1=input1.text.toString().trim().toBigDecimal()
            var inputdata2=input2.text.toString().trim().toBigDecimal()

             if(inputdata2.compareTo(BigDecimal.ZERO)==0){
                 input2.error="invalid input"
             }else {
                 result.text = inputdata1.divide(inputdata2, 2, RoundingMode.HALF_UP).toString();
             }
        }
    }

}

Explanation

First, we have used supportActionBar to change the background color of ActionBar. Now we applied setOnClickListener to all the buttons which are defined in the activity_main.xml. When the user clicks on any button, the inputIsNotEmpty() function will be called and this method will check whether the input field is empty or not. If any input field is empty then it will return a false value otherwise it will return a true value. If the inputIsNotEmpty() function returns a true value then statements that are written inside if() condition of a particular method will be executed. For example, if we click on the plus button then add() method will be called, and inside add() method first it will check inputIsNotEmpty() method to return a true or false value. If a value is true then the addition of input numbers will be displayed on textview. 

Step 3

Now click on the run button and launch the application

Output

Simple Calculator In Kotlin Output 

Conclusion

In this article, we have seen how to make a simple calculator using kotlin language. Thanks for reading and hope you like it. If you have any suggestions or queries on this article, please share your thoughts.

You can check out my other articles by clicking here.


Similar Articles