How to build a simple calculator app – full tutorial with code


Proceeding the Android Authority custom of establishing simple apps (see how to build a picture gallery app and how to create an SMS app), we’re going to build a simple however practical calculator app. Should you’re new to programming and feature by no means constructed an app sooner than, you will have to take a look at our earlier tutorial on writing your first Android app. This tutorial assumes that you’ve got no less than, a few fundamental revel in writing Android apps.

Similar to creating any non-trivial software, there’s greater than one means to do it, and in the event you get ten other programmers, chances are you’ll get ten alternative ways of writing a calculator (until all of them occur to be Android Authority readers *wink*). Your complete supply for the calculator app written under is to be had on github to be used, reuse and amendment up to you prefer.

Developing the undertaking

The very first thing to do is create a new venture through both clicking on “Get started a new Android Studio undertaking”, or ‘Record -> New -> New Challenge’.

Simple Calculator - new project

For this calculator tutorial, we decided on the EmptyActivity choice at the “Upload an Process to Cellular” monitor, and left the Task identify because the default MainActivity. At this aspect, your format hierarchy will have to appear to be the picture under. You have got a MainActivity inside of your challenge package deal, and an activity_main.xml document within the format listing.

Simple Calculator - heirarchy

Allow knowledge binding on your venture

For our pattern calculator, we will be able to setup our undertaking to use knowledge binding. The use of knowledge binding on this app merely is helping us refer to our widgets (Buttons, EditText and TextView) right away, slightly than discovering them with findViewById() strategies. To allow knowledge binding, you will have to upload the next line to your app build.gradle record.

android  ... dataBinding.enabled = actual ...

Simple Calculator - data binding

Designing the Calculator format

To allow knowledge binding in our activity_main.xml record calls for one remaining amendment. Wrap the generated root tag (in our case it used to be a RelativeLayout) inside of a format tag, making the format tag the brand new root tag.

<?xml model="1.0" encoding="utf-8"?>
<format> <RelativeLayout> ... </RelativeLayout>

The format tag is what signals the build gadget that this format record intends to use knowledge binding. The build gadget then generates a Binding elegance routinely for this format record. Because the objective xml document is known as activity_main.xml, the build device will generate a elegance referred to as ActivityMainBinding, which you’ll be able to reference on your app like some other Java elegance. The category identify is generated from the format document identify via capitalizing the primary letter of each and every phrase after an underscore, taking away all underscores, and including ‘Binding’ to the identify.

At this aspect, transfer to your record. Create a personal ActivityMainBinding example inside of your elegance, and within the onCreate() approach, delete the setContentView() line and exchange with the DataBindingUtil.setContentView() line within the code snippet beneath.

public elegance MainActivity extends AppCompatActivity  personal ActivityMainBinding binding; @Override safe void onCreate(Package savedInstanceState)  tremendous.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.format.activity_main); 

Working out the format widgets

There are four primary pieces in our calculator app. Those are:

  1. RelativeLayout – this merchandise governs how the opposite pieces are laid out, or displayed at the monitor. The RelativeLayout is used to place kid parts in relation to each and every different, or to itself.
  2. TextView – this merchandise is used to show textual content. Customers don’t seem to be anticipated to have interaction with this merchandise. The results of computations are displayed the use of a TextView.
  3. EditText – that is a more or less TextView that customers can edit, and alter the textual content. Then again, because the calculator lets in best a fastened set of inputs, we set the edit textual content to be non-editable. While the consumer clicks on numbers, we show the numbers within the EditText.
  4. Button – this merchandise lets in interplay through the consumer, and preferably, will have to reply to clicks by way of the consumer. We use buttons for the numbers, and operators within the calculator.

Construction the Calculator format

Simple Calculator - main layout

The calculator format is a bit lengthy. That is due to the truth that we have now to explicitly outline, and meticulously place, each and every of the buttons within the calculator. The snippet under is a condensed model of the activity_main format record

<format> <RelativeLayout xmlns:android="" xmlns:equipment="" android:identity="@+identity/activity_main" android:layout_width="match_parent" android:layout_height="match_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" equipment:context=""> <TextView android:identity="@+identity/infoTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="30dp" android:textSize="30sp" /> <EditText android:identity="@+identity/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@identity/infoTextView" android:enabled="fake" android:gravity="backside" android:strains="2" android:maxLines="2" android:textSize="20sp" /> <Button android:identity="@+identity/buttonSeven" taste="@taste/Widget.AppCompat.Button.Without borders" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@identity/editText" android:textual content="7" android:textSize="20sp" /> <Button android:identity="@+identity/buttonEight" taste="@taste/Widget.AppCompat.Button.Without borders" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@identity/editText" android:layout_toRightOf="@identity/buttonSeven" android:textual content="8" android:textSize="20sp" /> <Button android:identity="@+identity/buttonNine" taste="@taste/Widget.AppCompat.Button.Without boundary lines" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@identity/editText" android:layout_toRightOf="@identity/buttonEight" android:textual content="9" android:textSize="20sp" /> ... ... <Button android:identity="@+identity/buttonDot" taste="@taste/Widget.AppCompat.Button.Without borders" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@identity/buttonOne" android:textual content="." android:textSize="20sp" /> <Button android:identity="@+identity/buttonZero" taste="@taste/Widget.AppCompat.Button.Without borders" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@identity/buttonEight" android:layout_below="@identity/buttonTwo" android:textual content="0" android:textSize="20sp" /> <Button android:identity="@+identity/buttonEqual" taste="@taste/Widget.AppCompat.Button.Without boundary lines" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@identity/buttonNine" android:layout_below="@identity/buttonThree" android:textual content="=" android:textSize="20sp" /> <Button android:identity="@+identity/buttonDivide" taste="@taste/Widget.AppCompat.Button.Without boundary lines" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@identity/buttonNine" android:layout_toRightOf="@identity/buttonNine" android:textual content="/" android:textSize="20sp" /> <Button android:identity="@+identity/buttonMultiply" taste="@taste/Widget.AppCompat.Button.Without boundary lines" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@identity/buttonSix" android:layout_toRightOf="@identity/buttonSix" android:textual content="*" android:textSize="20sp" /> <Button android:identity="@+identity/buttonSubtract" taste="@taste/Widget.AppCompat.Button.Without boundary lines" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@identity/buttonThree" android:layout_toRightOf="@identity/buttonThree" android:textual content="-" android:textSize="20sp" /> <Button android:identity="@+identity/buttonAdd" taste="@taste/Widget.AppCompat.Button.Without borderlines" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@identity/buttonEqual" android:layout_toRightOf="@identity/buttonEqual" android:textual content="+" android:textSize="20sp" /> <Button android:identity="@+identity/buttonClear" taste="@taste/Widget.AppCompat.Button.Without boundary lines" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@identity/buttonAdd" android:layout_below="@identity/buttonAdd" android:layout_marginTop="@dimen/activity_vertical_margin" android:textual content="C" android:textSize="20sp" /> </RelativeLayout>

Calculator internals

Our calculator has two values, valueOne and valueTwo. Those values hang the numbers to be operated on. Each values are of sort double, so they may be able to hang numbers with and with out decimals. We set valueOne to the unique Double worth NaN (now not a quantity) for purposes in order to be clearer beneath.

 personal double valueOne = Double.NaN; personal double valueTwo;

This simple calculator can handiest carry out operations of both addition, subtraction, multiplication or department. So we outline four static chars to constitute those operations, and a CURRENT_ACTION variable, which holds the following operation we intend to carry out.

 personal static ultimate char ADDITION = '+'; personal static ultimate char SUBTRACTION = '-'; personal static ultimate char MULTIPLICATION = '*'; personal static ultimate char DIVISION = '/'; personal char CURRENT_ACTION;

In spite of everything, we use the DecimalFormat elegance to layout the output of our calculator. The decimal layout constructor lets in showing up to ten decimal puts.

 decimalFormat = new DecimalFormat("#.##########");

Dealing with button clicks (numbers)

Each time the consumer clicks a quantity (or dot), we merely need to upload that quantity to the editText. The code pattern under presentations how we accomplish this for quantity zero (0).

 binding.buttonZero.setOnClickListener(new View.OnClickListener()  @Override public void onClick(View view)  binding.editText.setText(binding.editText.getText() + "0");  );

Dealing with button clicks (operators)

Simple Calculator - with calculation

Coping with clicks on operators is a little other. We would really like to carry out any pending computations first. So we outline a computeCalculation approach. Inside of computeCalculation, if valueOne is a legitimate quantity, we learn valueTwo from the editText, and carry out the present queued operation. Then again, if valueOne is NaN, valueOne assigned the quantity within the editText.

 personal void computeCalculation()  if(!Double.isNaN(valueOne))  valueTwo = Double.parseDouble(binding.editText.getText().toString()); binding.editText.setText(null); if(CURRENT_ACTION == ADDITION) valueOne = this.valueOne + valueTwo; else if(CURRENT_ACTION == SUBTRACTION) valueOne = this.valueOne - valueTwo; else if(CURRENT_ACTION == MULTIPLICATION) valueOne = this.valueOne * valueTwo; else if(CURRENT_ACTION == DIVISION) valueOne = this.valueOne / valueTwo;  else  check out  valueOne = Double.parseDouble(binding.editText.getText().toString());  capture (Exception e)  

For each and every operator, we name computeCalculation() first, then set CURRENT_ACTION to the chosen operator, whilst for the equals ‘=’ operator, we name computeCalculation(), then transparent the contents of each valueOne and CURRENT_ACTION.

 binding.buttonAdd.setOnClickListener(new View.OnClickListener()  @Override public void onClick(View view)  computeCalculation(); CURRENT_ACTION = ADDITION; binding.infoTextView.setText(decimalFormat.layout(valueOne) + "+"); binding.editText.setText(null);  ); binding.buttonSubtract.setOnClickListener(new View.OnClickListener()  @Override public void onClick(View view)  computeCalculation(); CURRENT_ACTION = SUBTRACTION; binding.infoTextView.setText(decimalFormat.layout(valueOne) + "-"); binding.editText.setText(null);  ); binding.buttonMultiply.setOnClickListener(new View.OnClickListener()  @Override public void onClick(View view)  computeCalculation(); CURRENT_ACTION = MULTIPLICATION; binding.infoTextView.setText(decimalFormat.layout(valueOne) + "*"); binding.editText.setText(null);  ); binding.buttonDivide.setOnClickListener(new View.OnClickListener()  @Override public void onClick(View view)  computeCalculation(); CURRENT_ACTION = DIVISION; binding.infoTextView.setText(decimalFormat.layout(valueOne) + "/"); binding.editText.setText(null);  ); binding.buttonEqual.setOnClickListener(new View.OnClickListener()  @Override public void onClick(View view)  computeCalculation(); binding.infoTextView.setText(binding.infoTextView.getText().toString() + decimalFormat.layout(valueTwo) + " = " + decimalFormat.layout(valueOne)); valueOne = Double.NaN; CURRENT_ACTION = '0';  );

Congratulations! You have got finished your simple calculator Android app.

In any case

Should you run and use the above app, you’ll realize a few imaginable spaces of enhancements, corresponding to 1) click on an operator while the editText is obvious (i.e. with out getting into a quantity first), 2) permit the consumer proceed calculating after clicking the equals button.

As all the time, all the supply is to be had on github, and you’re loose (nay inspired) to adjust, and use, to your center’s content material. Hola within the feedback should you discovered this handy, and/or need to suggest an app for a long run tutorial.


Marshmallow Man, blog spiritual leader, has strived to make AppMarsh an independent and free blog from world monetary system. He and his followers are exiled by Google monster.