Saturday, 16 May 2015

Simple Calculator in Android

This post explains how you can create a simple calculator in android. You can download the code and use.

See xml class:
 

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















</LinearLayout >
        
See Java class:
 

 public class Calculator extends Activity implements OnClickListener {

   EditText etNum1;
   EditText etNum2;

   Button btnAdd;
   Button btnSub;
   Button btnMult;
   Button btnDiv;

   TextView tvResult;

   String oper = "";

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_calculator);

     // find the elements
     etNum1 = (EditText) findViewById(R.id.etNum1);
     etNum2 = (EditText) findViewById(R.id.etNum2);

     btnAdd = (Button) findViewById(R.id.btnAdd);
     btnSub = (Button) findViewById(R.id.btnSub);
     btnMult = (Button) findViewById(R.id.btnMult);
     btnDiv = (Button) findViewById(R.id.btnDiv);

     tvResult = (TextView) findViewById(R.id.tvResult);

     // set a listener
     btnAdd.setOnClickListener(this);
     btnSub.setOnClickListener(this);
     btnMult.setOnClickListener(this);
     btnDiv.setOnClickListener(this);

   }

   @Override
   public void onClick(View v) {
     // TODO Auto-generated method stub
     float num1 = 0;
     float num2 = 0;
     float result = 0;

     // check if the fields are empty
     if (TextUtils.isEmpty(etNum1.getText().toString())
         || TextUtils.isEmpty(etNum2.getText().toString())) {
       return;
     }

     // read EditText and fill variables with numbers
     num1 = Float.parseFloat(etNum1.getText().toString());
     num2 = Float.parseFloat(etNum2.getText().toString());

     // defines the button that has been clicked and performs the corresponding operation
     // write operation into oper, we will use it later for output
     switch (v.getId()) {
     case R.id.btnAdd:
       oper = "+";
       result = num1 + num2;
       break;
     case R.id.btnSub:
       oper = "-";
       result = num1 - num2;
       break;
     case R.id.btnMult:
       oper = "*";
       result = num1 * num2;
       break;
     case R.id.btnDiv:
       oper = "/";
       result = num1 / num2;
       break;
     default:
       break;
     }

     // form the output line
     tvResult.setText(num1 + " " + oper + " " + num2 + " = " + result);
   }
 }

      

No comments:

Post a Comment