Simple Calculator



Objective:

This is the simple calculator to demonstrate getting input text from user. When user press the corresponding button, the result will be displayed.

Project Info:

Application Name: CustomFonts
Build SDK: API 15, Android 4.0.3 (ICS)
Miniumum Required SDK: API 8, Android 2.2 (Froyo)
Additional Files created: None
Default Files edited: Two

1. Create default project. The project tree will look like this.




2. Edited MainAcitvity.java
package com.example.simplecalculator;

import java.text.DecimalFormat;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    Button btnAddition, btnSubtraction; //create Button variable // treat it as variable
    EditText etFirstNumber, etSecondNumber; //create EditText variable
    TextView tvResult; //create TextView variable
    double firstNumber, secondNumber, result; //crate double variable
    String output; //crate string variable

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnAddition = (Button) findViewById(R.id.btnAdd); //link Button variable with XML Button// id is from XML file
        btnSubtraction = (Button) findViewById(R.id.btnSub);
        etFirstNumber = (EditText) findViewById(R.id.etFn);//link EditText variable with XML EditText 
        etSecondNumber = (EditText) findViewById(R.id.etSn);
        tvResult = (TextView) findViewById(R.id.tvR);//link TextView variable with XML TextView

        btnAddition.setOnClickListener(new OnClickListener() { //Assign Button to setOnClickListener
            public void onClick(View v) {
                if (etFirstNumber.length() > 0) { //check whether user put any value in the filed
                    firstNumber = Double.parseDouble(etFirstNumber.getText()//if true, assign value to firstNumber variable
                            .toString());//from String to double then assign to firstNumber variable
                } else
                    Toast.makeText(getBaseContext(), //if false, display Toast to user
                            "Please add some number in the first field",
                            Toast.LENGTH_SHORT).show();
                if (etSecondNumber.length() > 0) { //similar to first number//checking the input
                    secondNumber = Double.parseDouble(etSecondNumber.getText()
                            .toString());
                } else
                    Toast.makeText(getBaseContext(),
                            "Please add some number in the second field",
                            Toast.LENGTH_SHORT).show();
                
                result = firstNumber + secondNumber; //value addition
                DecimalFormat round = new DecimalFormat("###.##");//formating double value to 2 decimal
                output = round.format(result); //format the result
                tvResult.setText(output); //display the formatted string value
            }
        });

        btnSubtraction.setOnClickListener(new OnClickListener() { //Assign Button to setOnClickListener//in this case, subtraction button
            public void onClick(View v) {
                if (etFirstNumber.length() > 0) {
                    firstNumber = Double.parseDouble(etFirstNumber.getText()
                            .toString());
                } else
                    Toast.makeText(getBaseContext(),
                            "Please add some number in the first field",
                            Toast.LENGTH_SHORT).show();
                if (etSecondNumber.length() > 0) {
                    secondNumber = Double.parseDouble(etSecondNumber.getText()
                            .toString());
                } else
                    Toast.makeText(getBaseContext(),
                            "Please add some number in the second field",
                            Toast.LENGTH_SHORT).show();
                result = firstNumber - secondNumber; //all same as above listener. only this line is for subtraction.
                DecimalFormat round = new DecimalFormat("###.##");
                output = round.format(result);
                tvResult.setText(output);

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

3. Edit activity_main.xml

<RelativeLayout 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" >

    <EditText
        android:id="@+id/etFn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="numberDecimal|numberSigned" /> <!-- Accept both decimal and singed number -->

    <EditText
        android:id="@+id/etSn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:ems="10"
        android:inputType="numberDecimal|numberSigned"
     >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnSub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="Subtraction" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:text="Addition" />

    <TextView
        android:id="@+id/tvR"
        android:text="0.00"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnSub"
        android:layout_centerHorizontal="true"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginTop="54dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnSub"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:text="Result:"
        android:textAppearance="?android:attr/textAppearanceMedium" /> <!-- Medium size; -->
        <!-- android:textSize = "50sp" this can be done to change font -->
</RelativeLayout>

Note:



Download Project:

http://osdevlab.googlecode.com/svn/trunk/tut2.0/










No comments:

Post a Comment