A.I, Data and Software Engineering

Build an android calculator in 5 minutes

B
Mobile Calculator

This tutorial, we demonstrate how to use Android Kotlin to build a mobile calculator in just 5 minutes. It is really simple and fun. You can watch a video tutorial at the end of this post.

Create an android project with Kotlin

From Android Studio welcome page, select “Create a new project” and follow the instruction on screen.

Enter the app name, package name and use Kotlin for the language option.

Select the desired API version, e.g. 5.0. It is recommended that your app can cover at least 80%+ of all devices on the market.

Android project using with Kotlin
Create an empty project using with Kotlin

Create the graphical user interface of the calculator

Go to res/layout/main_activity.xml and change the generated root layout to GridLayout.

Horizontally, we divide the screen into 6 parts: 1 display row and 5 button rows. The height of the display row is twice as other rows. The width of the button columns is 1/4 of the screen width. Therefore, we will have 7 \times 4 grids. The design of the grid view should look like this.


12345.6 (span 4 cols)
DelC/×
789
456+
123= (span 2 rows)
0 (span 2 cols).

As we want the width and height to be adjusted automatically, we will set their value to 0dp. A typical button in the grid view should look like this.

<TextView android:layout_width="0dp"
        android:layout_height="0dp"
        style="@style/cell_style"
        android:text="Del"
        />

We store the shared style in the styles.xml file so that other buttons can The style for the result textview is as follow.

<style name="result_style">
        <item name="android:layout_row">0</item>
        <item name="android:layout_rowSpan">2</item>
        <item name="android:layout_rowWeight">2</item>
        <item name="android:layout_column">0</item>
        <item name= "android:layout_columnSpan">4</item>
        <item name= "android:gravity">bottom|right</item>
        <item name="android:text">12345</item>
        <item name= "android:textSize">50sp</item>
        <item name="android:background">@color/colorAccent</item>
    </style>

The buttons have similar style except their weight and text alignment. We can also handle the click event in the style, i.e.

<item name="android:onClick">onClick</item>
<style name="cell_style">
        <item name="android:layout_rowWeight">1</item>
        <item name="android:layout_columnWeight">1</item>
        <item name= "android:gravity">fill</item>
        <item name= "android:textSize">35sp</item>
        <item name="android:textAlignment">center</item>
        <item name="android:background">#FFD600</item>
        <item name="android:layout_margin">1dp</item>
        <item name="android:onClick">onClick</item>
    </style>

Integrate Javaluator for process Infix notation

To get the result of a mathematical expression, we need a tool to process the infix notation which is more human-readable than prefix and post-fix ones.

infix expression
infix notation

We will use javaluator for Kotlin from Maven repository. Go the the link and copy the code and paste it in the dependencies section of the gradle script (:app) and sync.

implementation("com.fathzer:javaluator:3.0.3")

Handle click events and result

There are couples of tasks need to consider:

  • delete the text if del button is clicked
  • append to the result if a number or operator is clicked.
  • handle the case when user presses 2 operators consecutively.
  • Finally, we should update the result when users press = button.

The code snippet for all of these tasks is.

override fun onClick(v: View?) {
        var tv = v as TextView
        var resultTV = findViewById<TextView>(R.id.resultTV)
        var oldText = resultTV.text.toString()
        when(tv.text.toString()){
            "Del" -> {
                if(oldText.length > 0){
                    var newText = oldText.substring(0, oldText.length - 1)
                    resultTV.setText(newText)
                }
            }
            "" -> {resultTV.setText(null)}
            "=" -> {
                var evaluator = DoubleEvaluator()
                var expression = resultTV.text.replace(Regex("×"), "*")
                var result = evaluator.evaluate(expression)
                resultTV.setText(result.toString())
            }
            else -> {
                var toAppendString = tv.text.toString()
                if(isOperator(toAppendString[0]) && isOperator(oldText[oldText.length - 1])){
                    oldText = oldText.substring(0, oldText.length - 1)
                }
                var newText = oldText + toAppendString
                resultTV.setText(newText)
            }
        }
    }

Video tutorial

Must see links

Add comment

💬

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Categories