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.

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

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

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.

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.

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.

Pin It on Pinterest

Newsletters

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.