What will you learn?
- Using OnCLickListener to interact with buttons. You can read about OnClickListener in detail before proceeding, although it isn’t required.
Note: Find the full code of the android calculator project towards the end of the post. Read the entire post for further clarification and explanations.
Contents
Building the interface of the simple calculator in Android
As with all applications, we should always start by creating the interface. For the android calculator app, we require the following elements.
- TextView
- Buttons
That’s it. We use the textView to show users the numbers they have written and also to display the result of the calculations we are going to do.
Each of the numbers will have a different button, from 0-9 and we will have four additional buttons for addition, subtraction, multiplication and division. Other than this, we require a button to calculate the operation, a button for decimals, and a button to clear the display.
Requirements
1. EditText: To display numbers and the result.
2. Button: Numbers 0-9
3. Button: Operational buttons (+, -, *, /, =)
4. Button: Decimal button
5. Button: Clear display button.
Here’s a screenshot of what the code at the bottom would look like if you were to paste it in your activity_main.xml file.
Coding the Functionality of our simple calculator
Step 1: Creating objects for our elements
In your Java file, which is almost always MainActivity.java by default, head on over to the MainActivity extends AppCompatActivity class. Inside that, create objects for all of your 15+ buttons and an object for your EditText. If you are unsure of how to do that, then copy and paste the following code. If you are uncertain of where to post this code, refer to the complete code tutorial by scrolling to the bottom.
Button btn_1, btn_2, btn_3, btn_4, btn_5, btn_6, btn_7, btn_8, btn_9, btn_0, btn_Add, btn_Sub, btn_Mul, btn_Div, btn_calc, btn_dec, btn_clear;
EditText ed1;
Next, we will need two float values to store the first number and second number. We use float instead of integers because integers only hold whole numbers while float can hold decimal numbers too.
float Value1, Value2;
And finally, we need four boolean variables to check what operation is going on. A boolean variable returns only two variables — a true and a false. We check which button is pressed and use this boolean variable to perform the corresponding function.
boolean mAddition, mSubtract, mMultiplication, mDivision ;
Step 2: Fetching values from the elements into the working of our app
Inside the onCreate function, we will fetch all values and assign them to our objects. We do this by the following code
btn_0 = (Button) findViewById(R.id.btn_0);
Here, we are fetching the value of ‘btn_0’, which is the ID of our button zero, and storing it in the object ‘btn_0’ that we created earlier. Though they are named the same, Android Studio can identify the correct one. But if it gets confusing for you, feel free to give either one of them any other names.
We do the same with our EditText.
ed1 = (EditText) findViewById(R.id.edText1);
Step 3: Changing the EditText value by pressing the buttons.
Here’s the code
btn_1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ed1.setText(ed1.getText()+"1"); } });
We use OnClickListener for this part of the program. This is what happens when you push one. The editText, first already fetches the value that it is already displaying, null in this case, and then adds 1 to it. If we don’t fetch the existing value, then it will become impossible to enter multiple digit numbers.
Do this on repeat mode for each of the numbers as well as the decimal. These are input buttons, and the code is the same for all. But remember to replace “1” with the appropriate value of the button you are adding to it.
Step 4: The functional buttons
Here’s the code we are using for multiplication.
btn_Mul.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Value1 = Float.parseFloat(ed1.getText() + ""); mMultiplication = true ; ed1.setText(null); } });
We are using our first float value ‘Value1’ here. We use the simple function getText() to do that. Here since we pressed the multiplication button, we set its boolean equivalent variable to true. You will see how this is helpful in the ‘calculate’ button coding.
Now since after we press the multiplication button, we have to input another number. We set EditText to display the null value.
We do the same process for Addition, Subtraction, and Division. The only difference is that their respective boolean values will be set to True.
Step 5: Calculating, the actual functionality
Here’s the code of what happens when you or someone else presses the ‘=’ button after inputting another integer.
btn_calc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Value2 = Float.parseFloat(ed1.getText() + ""); if (mSubtract == true){ ed1.setText(Value1 - Value2 +""); mSubtract=false; } } });
If you are a quick reader and just copy-pasting code, then the above code is not the complete code, it only checks for subtraction.
A couple of things are happening here. Firstly, we are fetching the value that you entered after pressing one of the four functional buttons (+, -, *, /) and storing it in the float variable ‘Value2’.
Next, we execute an if-condition to check whether our four boolean values are true and then run its subsequent code. In the above example, we are executing only the if condition for subtraction. For the full code, refer to the code below.
The main operation is happening in the ‘ed1.setText(Value1 – Value2 + “”);’ line. For other functions, replace the – sign with others.
Now write the code for all functions and run the app. If you do the first operation
2 + 2
You’ll get the right answer as
4
But there are still a lot of flaws in this app. And that’s why this is a basic version of the app and not an advanced debugged version.
Flaws of this android calculator app that are not covered in this post
- We are only using two float values. So 2 + 2 will be 4. But if you do 2 + 3 + 4, you will get 7. It will store only the last two input values.
- The app crashes when we press any one of the functional buttons. This may require either and if-condition statement or a try-exception. Something that we will learn later on in an advanced calculator post
Check out some more of our tutorials on Android.
1 Use Intent to start a new activity
2 Play Audio File using MediaPlayer
4 Study about different Layouts in Android and which one to use when.
Full Code for the User Interface for Android Simple Calculator App
Full Code Tutorial for the Functionality of Android Calculator App
Remember to change your package name to what you are using!