Home > DeveloperSection > Beginner > Simple Calculator App in Android

Simple Calculator App in Android


Android Android Activity  Android Layout  Android Emulator  Android Edittext 
Ratings:
1 Comment(s)
 5017  View(s)
Rate this:

Simple Calculator App in Android


In my previous post we implemented a simple app in which an invisible view is appeared when a user click on the show button(How to Show invisible text on button Click in android)

In this article we are going to implement a simple calculator App with basic functionality such as addition, subtraction, multiplication and division.

Pre-Requisites:

1.       Ellipse SDK

2.       Android SDK

3.       ADT plugin

Install and configure the above utilities.

Now create a new Android project namely “SimpleCalculator”.

Add Widgets to our GUI:

Now, we need to add views in our view groups, i.e. add widgets to our GUI.

 We need

1.      Two EditText  to enter our values(operands)

2.      One Spinner to choose which operation to perform i.e. Addition, subtraction, Multiplication, Division. (spinner widget is used to implement drop-down list in android)

3.      A button which will be clicked to perform the operation.

4.      One more  EditText widget to show the result

For this, navigate to res/Layout/main.xml from package explorer in Eclipse. Open main.xml

Add following code into it:

 

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >

   

    <LinearLayout

        android:orientation="horizontal"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content">

       

   

 

    <EditText

        android:id="@+id/edtNumber1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:inputType="numberDecimal"

        android:hint="@string/hntNumber1"

    />

   

    <Spinner

        android:id="@+id/sprOperator"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:entries="@array/sprItems"

    />

   

     <EditText

        android:id="@+id/edtNumber2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:inputType="numberDecimal"

        android:hint="@string/hntNumber2"

    />

     </LinearLayout>

    

       <Button

        android:id="@+id/btnResult"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:hint="@string/lblBtnResult"

    />

    

    <EditText

        android:id="@+id/edtResult"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:inputType="numberDecimal" />

 

</LinearLayout>

 

 

Now our app GUI will look something like this:

 

 

Adding String values for GUI widgets:  

 

Now we need to add string values for our GUI widgets

Now, open res/values/string.xml from package explorer and add following code in it:

 

 

<?xml version="1.0" encoding="utf-8"?>

<resources>

 

    <string name="app_name">SimpleCalculator</string>

    <string name="action_settings">Settings</string>

    <string name="hello_world">Hello world!</string>

    <string name="hntNumber1">First No. </string>

    <string name="hntNumber2">Second No.</string>

    <string name="lblBtnResult">Result</string>

    <string-array name="sprItems">

        <item>+</item>

        <item>-</item>

        <item>x</item>

        <item>/</item>

    </string-array>

</resources>

 

 

 

We need to store spinners (drop-down) values i.e. signs (+, -, x, /) in a string – array.

 

 

Adding behavior to the Button:

 To add behavior to our app we need to perform the operations on the input value on button click and show the correct result.

So we implement actions on button click by OnClickListener().

So our final code for  mainActivity class will look like this:

 

package com.example.simplecalculator;

 

 

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Spinner;

import android.view.View.OnClickListener;;

 

public class MainActivity extends Activity {

    /** Called when the activity is first created. */

    @Override

                protected void onCreate(Bundle savedInstanceState) {

                                super.onCreate(savedInstanceState);

                                setContentView(R.layout.activity_main);

 

        // get the button’s reference

        Button btn = (Button) findViewById(R.id.btnResult);

 

        // Defining onclick listener for finding the result

        btn.setOnClickListener( new OnClickListener() {

 

                @Override

           public void onClick(View v) {

 

             // Get view references of all the UI widgets

                Spinner spr = (Spinner) findViewById(R.id.sprOperator);

                EditText edtNumber1 = ( EditText) findViewById(R.id.edtNumber1);

                EditText edtNumber2 = ( EditText) findViewById(R.id.edtNumber2);

                EditText edtResult = ( EditText) findViewById(R.id.edtResult);

 

                String selectedItem = (String) spr.getSelectedItem();

 

                 //Perform the operations based on selected signs strings

 

                if(selectedItem.trim().equals("+")){

                    float result = Float.parseFloat(edtNumber1.getText().toString())  + Float.parseFloat(edtNumber2.getText().toString());

                    edtResult.setText(Float.toString(result));

                }else if(selectedItem.trim().equals("-")){

                    float result = Float.parseFloat(edtNumber1.getText().toString())  - Float.parseFloat(edtNumber2.getText().toString());

                    edtResult.setText(Float.toString(result));

                }else if(selectedItem.trim().equals("x")){

                    float result = Float.parseFloat(edtNumber1.getText().toString())  * Float.parseFloat(edtNumber2.getText().toString());

                    edtResult.setText(Float.toString(result));

                }else if(selectedItem.trim().equals("/")){

                    float result = Float.parseFloat(edtNumber1.getText().toString())  / Float.parseFloat(edtNumber2.getText().toString());

                    edtResult.setText(Float.toString(result));

                }

           }

 

        });

 

    }

}

 

Now run the project, emulator will start and enter your inputs in the text fields

 

Now select the operation you want to perform (i.e. addition, subtraction, multiplication, division) from the drop –down list

 

Click on Result button. Done! This will show the result in the result Text box.


Having equipped with the concept of Spinner and other UI components next we move to list view and model popups in Show List View in Model pop-up on Button click in Andriod


android

By Amar Kamble on   one year ago
android

Don't want to miss updates? Please click the below button!

Follow MindStick