Home

Build Simple Calculator App – Android Studio Tutorial

By Ajin Asokan in Blog . 6 min read
Sep 27, 2016

In previous tutorial we saw how to make the smallest Android app from scratch. If you haven’t read it please read it and come back because this tutorial is based on it. In this tutorial I will be showing you how to build a simple calculator based on HTML, JavaScript, CSS and WebView.

You may already know that HTML is a language used to design web pages. Javascript is does the programming part in the web sites and makes websites dynamic, that means interactive to the user. And CSS does the styling of the HTML page and makes it beautiful. WebView is a component, just like TextView as we saw in the previous tutorial, to show HTML contents or websites inside the app, basically a miniature browser.

Here we are going to design a calculator using HTML, style it a bit using CSS, make it do the math using javascript and integrate it to the smallest app we built in the previous chapter using WebView.

So lets start. First thing you need to do is take a copy of the existing Android Studio project folder of the app we designed in smallest app project, so that you have a backup of the original. You can also download it from my github repo.

AndroidManifest.xml

Lets make some changes here. First change the label property of application tag and activity tag to Calculator. Then change the theme property of application to @android:style/Theme.NoTitleBar. So it will not show the ugly title bar on top of the activity.

It should look something like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myapp">
    <application
        android:label="Calculator"
        android:theme="@android:style/Theme.NoTitleBar">

        <activity
            android:name=".MainActivity"
            android:label="Calculator" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

        </activity>

    </application>
</manifest>

activity_main.xml

Open the layout file. Remove the TextView we used to show Hello World. Then add a WebView component as shown below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/html"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>

</LinearLayout>

As you can see the width and height is set to match_parent so the WebView will be filled in the screen. That means only the HTML contents will be seen on the screen. And the id of WebView is set to html so that I can access it in the code.

MainActivity.java

In our code all we need to do is to initialize the WebView to load our HTML page. Here is the complete code:

package com.myapp;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView html = (WebView) findViewById(R.id.html);
        html.getSettings().setJavaScriptEnabled(true);
        html.loadUrl("file:///android_asset/index.html");
    }
}

Lets see what those extra 3 lines do. In first we actually link the WebView in layout file with id as html to the code (I will explain why we need this in upcoming chapters). In second line we change the settings and enable the javascript functionality in the WebView. We need this because our app does the calculations using javascript. In third line the app loads the html page. It is kept in the assets folder of the app. The scheme string file:/// denotes that the file is store in the phone itself not in the internet.

Thats all the coding stuff. Now lets design the calculator.

The Calculator

This is an HTML page. It has a specific structure. The entire document is inside an html tag. The content which is shown in browser is inside body tag. Here is the complete html page for our calculator:

<html>
<body>
<style>
table,button,input{
    height: 100%;
    width: 100%;
    font-size: 25px;
}
</style>

<table>
    <tr>
        <td colspan=4><center>CALCULATOR</center></td>
    </tr>
    <tr>
        <td colspan=3><input type=text id="display"></td>
        <td><button>Clear</button></td>
    </tr>
    <tr>
        <td><button>1</button></td>
        <td><button>2</button></td>
        <td><button>3</button></td>
        <td><button>/</button></td>
    </tr>
    <tr>
        <td><button>4</button></td>
        <td><button>5</button></td>
        <td><button>6</button></td>
        <td><button>*</button></td>
    </tr>
    <tr>
        <td><button>7</button></td>
        <td><button>8</button></td>
        <td><button>9</button></td>
        <td><button>-</button></td>
    </tr>
    <tr>
        <td><button>.</button></td>
        <td><button>0</button></td>
        <td><button>=</button></td>
        <td><button>+</button></td>
    </tr>
</table>

<script src="jquery.js"></script>

<script type="text/javascript">
    $('button').click(function(){
        if($(this).html()=='='){
            $('#display').val(eval($('#display').val()));
        }else if ($(this).html()=='Clear'){
            $('#display').val('');
        }else{
            $('#display').val($('#display').val() + $(this).html());
        }
    });
</script>
</body>
</html>

Inside the body tag the first thing you can see is the style tag. This is where we write the css styles. Here the style is applied to table,buttons and input textbox and it makes the width and height to 100% and font-size to 25 pixels.

Next part is the table. It will not appear as a table because we didn’t set a border here. tr is the table row and td is the table column. So there are 6 rows. In last 4 rows there are 4 columns. In first row the heading column spans to 4 columns. This is defined by the colspan property. In next row 3 columns are occupied by the text box with id set as display and a button to clear the contents.

Last part is the javascript. You can see there are two script components. One is for including jQuery library and other is the calculator code. jQuery is a javascript framework that makes javascipt coding very easy. In second script part what we do is whenever a button is clicked we check the text in the button and perform appropriate task.

We get the text using the function $(this).html() where this denotes the button. If it is = then calculation has to be done. The value inside the text box is retrieved using $(‘#display’).val() function where #display denotes the element with id display. eval function calculates the output. Calling value function with an input sets the value. That means $(‘#display’).val(‘xyz’) will set the text inside the text box with id display as xyz. In short if you press the button with = as text then it will calculate the problem written in the text box and print it inside it.

If the button was not equal button then next check is whether it is Clear button. If it is Clear then the value of display is set to blank. In all other cases the button is a digit or symbol. So what we do is append that symbol to the display content.

Thats it. Save this file as index.html somewhere. But in order to do make this work you also need the jquery file. Here is the link. Open it and save it as jquery.js. Now goto the project folder. Inside it goto app » src » main folder. You can see java, res and AndroidManifest.xml in there. Create another folder with name assets and copy our index.html and jquery.js to this assets folder. It should look something like this:

Android Studio WebView Assets

Build Project

Now come back to Android Studio. The project file structure will have updated like this:

Android Studio Calculator App Project Structure

Done. Now build the APK and install it in your phone and run it. Here is how it works in my phone:

Android Studio Simple Calculator App

Did it work? Cool, isn’t it? Try something else by modifying this app. Let me know about your experiments in the comments.

To be continued..