Android Tutorial for Beginners – Create Simple Calculator

Seagatesite – I’ll share about android tutorial on Android Tutorial for Beginners – Create Simple Calculator. Continuing my previous article about the Introduction Android Studio for Beginners, as a warm up we learn to understand the android programming ranging from the simplest applications first. I will create a simple calculator as a tutorial for beginners to learn android. Simple calculator that we will create will be able to do mathematical calculations operations, such as addition, subtraction, multiplication and division.

A simple calculator represents the concept of an overall application. There is input, process and output. By understanding this simple calculator application creation, allows us to understand how to learn android programming.

Android application that we will create more or less like the following picture

Learning Android Simple Calculator Project

There are 3 EditText, 4 Button, 3 TextView, users can enter any number in the field provided, then if the button is clicked will perform its function and if there is an error displays an error message via toast

Lets begin How to Create Simple Calculator for Beginners

1. Create new android project as CalcAPP ( File -> New -> New Project)

Create New Project Learning Android Create Simple Calculator Applications For Beginners
Choose Phone And Tables Minimum Sdk Learning Android Create Simple Calculator Applications For Beginners
Choose Blank Activity Learning Android Create Simple Calculator Applications For Beginners
Customize Activity Learning Android Create Simple Calculator Applications For Beginners

2. Change RelativeLayout to be LinearLayout by changing the text on the display as shown below.

Change Relativelayout To Linearlayout Learning Android Create Simple Calculator Applications For Beginners

Or copy this below

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical">
</LinearLayout>

Then add a LinearLayout (horizontal) by 4 units to the root layout (LinearLayout) and each TextView, EditText and Button into each LinearLayout as shown below

Create Edittext Textview Button Learning Android Create Simple Calculator Applications For Beginners

Then edit each widget on the layout by adding text and ID. Or you can copy the following script on activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical">
    <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:id="@+id/linearLayout4">

        <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Simple Calculator" android:id="@+id/textView" />
    </LinearLayout>
    <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linear24" android:layout_below="@+id/linearLayout4" android:layout_alignParentLeft="true" android:layout_alignParentStart="true">

        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Number 1" android:id="@+id/textView1" />

        <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText1" android:layout_weight="1" android:inputType="number" />
    </LinearLayout>

    <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout" android:layout_below="@+id/linear25" android:layout_alignParentLeft="true" android:layout_alignParentStart="true">

        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Number 2" android:id="@+id/textView2" />

        <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText2" android:layout_weight="1" android:inputType="number" />
    </LinearLayout>

    <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout2" android:layout_below="@+id/linearLayout" android:layout_alignParentLeft="true" android:layout_alignParentStart="true">

        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:id="@+id/btnplus" />

        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-" android:id="@+id/btnmin" />

        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="*" android:id="@+id/btnmultiple" />

        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="/" android:id="@+id/btndiv" />
    </LinearLayout>
    <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout3">

        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Result" android:id="@+id/textView3" />
        <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editTextResult" android:layout_weight="1" android:inputType="number" />
    </LinearLayout>
</LinearLayout>

Why Should change of RelativeLayout be LinearLayout?

I quote from the site http://themasterworld.com/

Linear layout is one of the most important fundamental in android that provides facilities to developer to create there UI. Linear layout is the layout that aligns all layout in one direction horizontal and vertical. Orientation is available in linear layout. vertical and horizontal. It is used for situation when children are rendered from left to right and top to bottom.

LinearLayout make your application look more neat and powerful, easy to set up the display in a linear layout.

3. Add function as addition, subtraction, multiplication and division on MainActivity.java like the following code

package com.example.sigit.calcapp;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    Button bplus,bmin,bmultiple,bdiv;
    EditText in1,in2,result;

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

        in1 = (EditText) findViewById(R.id.editText1);
        in2 = (EditText) findViewById(R.id.editText2);
        result = (EditText) findViewById(R.id.editTextResult);
        bplus = (Button) findViewById(R.id.btnplus);
        bmin = (Button) findViewById(R.id.btnmin);
        bmultiple = (Button) findViewById(R.id.btnmultiple);
        bdiv = (Button) findViewById(R.id.btndiv);

        bplus.setOnClickListener(this);
        bmin.setOnClickListener(this);
        bmultiple.setOnClickListener(this);
        bdiv.setOnClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v){
        Toast pieceToast=null;
        switch (v.getId()) {
            case R.id.btnplus:
                String val1 = in1.getText().toString();
                String val2 = in2.getText().toString();
                if(val1.equals("") || val2.equals("")){
                    pieceToast= Toast.makeText(getApplicationContext(), "Please fill the number", Toast.LENGTH_SHORT);
                    pieceToast.show();
                    break;
                }
                String retval = pluscalc(val1,val2);
                result.setText(retval);
                break;
            case R.id.btnmin:
                String min1 = in1.getText().toString();
                String min2 = in2.getText().toString();
                if(min1.equals("") || min2.equals("")){
                    pieceToast= Toast.makeText(getApplicationContext(), "Please fill the number", Toast.LENGTH_SHORT);
                    pieceToast.show();
                    break;
                }
                String retvalmin = mincalc(min1, min2);
                result.setText(retvalmin);
                break;
            case R.id.btnmultiple:
                String multi1 = in1.getText().toString();
                String multi2 = in2.getText().toString();
                if(multi1.equals("") || multi2.equals("")){
                    pieceToast= Toast.makeText(getApplicationContext(), "Please fill the number", Toast.LENGTH_SHORT);
                    pieceToast.show();
                    break;
                }
                String retvalmulti = multiplecalc(multi1, multi2);
                result.setText(retvalmulti);
                break;
            case R.id.btndiv    :
                String div1 = in1.getText().toString();
                String div2 = in2.getText().toString();
                if(div1.equals("") || div2.equals("")){
                    pieceToast= Toast.makeText(getApplicationContext(), "Please fill the number", Toast.LENGTH_SHORT);
                    pieceToast.show();
                    break;
                }
                String retvaldiv = divcalc(div1, div2);
                result.setText(retvaldiv);
                break;
        }
    }
    private String pluscalc(String a, String b){
        Double d1 = Double.parseDouble(a);
        Double d2 = Double.parseDouble(b);
        Double dhasil = d1 + d2;
        String shasil = String.valueOf(dhasil);
        return shasil;
    }
    private String mincalc(String a, String b){
        Double d1 = Double.parseDouble(a);
        Double d2 = Double.parseDouble(b);
        Double dhasil = d1 - d2;
        String shasil = String.valueOf(dhasil);
        return shasil;
    }
    private String multiplecalc(String a, String b){
        Double d1 = Double.parseDouble(a);
        Double d2 = Double.parseDouble(b);
        Double dhasil = d1 * d2;
        String shasil = String.valueOf(dhasil);
        return shasil;
    }
    private String divcalc(String a, String b){
        Double d1 = Double.parseDouble(a);
        Double d2 = Double.parseDouble(b);
        Double dhasil = d1 / d2;
        String shasil = String.valueOf(dhasil);
        return shasil;
    }

}

4.  Your application is ready for use, please Debug your App by clicking Run -> Debug App (Shift + F9)

Build App Android

Tutorial Learning Android Create Simple Calculator Applications For Beginners

Select your device emulator, in this example, I use genymotion as android emulator. How to install genymotion on linux / windows I will discuss in a future article. Results of a simple calculator application will be as follows

Learning Android Create Simple Calculator Applications For Beginners 2

Explanation :

Layout interfaces on android applications created using programming language XML. In the simple calculator program that was created above, has a parent component (root), which a parameter LinearLayout has layout_width = match_parent and layout_height = match_parent. So this application has a fullscreen view. Different from the parent, LinearLayout contained within the parent root has layout_width parameter = match_parent and layout_height = wrap_content. Match_parent parameter identifies wide layout adapts to the parent component, whereas wrap_content parameter identifies the size of the layout adjusts its components.

Then in MainActivity.java, at the beginning of the line is declared objects such as buttons and EditText. Each activity has onCreate() method. This method was first executed by the system when the application is running. Each activity also has a layout’s partner. OnCreate() method used to declare components or widgets anything contained in the layout’s partner.

Each button be activated with setOnClickListener() method. SetOnclickListener() method will be paired with the onClick() method , which is tasked to handle the process if the button’s clicked.

There are two ways to implement the OnClickListener method on android. for example as the following code line

Example one

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btnone = (Button)findViewById(R.id.Button1);
        btn1.setOnClickListener(new OnClickListener() {
	public void onClick(View v) {
		Toast pieceToast= Toast.makeText(getApplicationContext(), "Button One Clicked", Toast.LENGTH_SHORT);
		pieceToast.show();		
	}
        });
        Button btntwo = (Button)findViewById(R.id.Button2);
        btntwo.setOnClickListener(new OnClickListener() {
	public void onClick(View v) {
		Toast pieceToast= Toast.makeText(getApplicationContext(), " Button Two Clicked", Toast.LENGTH_SHORT);
		pieceToast.show();		
	}
          });

Example two

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bplus = (Button) findViewById(R.id.btnplus);
        bmin = (Button) findViewById(R.id.btnmin);

        bplus.setOnClickListener(this);
        bmin.setOnClickListener(this);
}

 @Override
    public void onClick(View v){
        Toast pieceToast=null;
        switch (v.getId()) {
            case R.id.btnplus:
                      your code here
                      break;
            case R.id.btnmin
                      your code here
                      break;

All of the above is true, but the second way is more simple than the first example.

In other opportunity I will discuss how to create Android APK with Android Studio and how to add the Android App Icon

Thus article about Android Tutorial for Beginners – Create Simple Calculator , hope useful.

The following two tabs change content below.
This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Leave a Comment

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

%d bloggers like this: