[Android] Beginner Tutorials – Lesson 19. Creating a simple calculator

Translated by Taras Leskiv (http://android-by-example.blogspot.com/)

We will try to develop the simplest calculator, which takes two numbers and applies addition, subtraction, multiplication and division operations to them. The result is displayed as a complete expression.

Let’s create an project:

Project name: P0191_SimpleCalculator
Build Target: Android 2.3.3
Application name: SimpleCalculator
Package name: ru.startandroid.develop.simplecalculator
Create Activity: MainActivity

Open main.xml and draw the screen:

We have two input fields here, four buttons and a text field for output. Have a look at inputType attribute for EditText. It defines the type of the content. I’ve specified numberDecimal – that is field can only contain numbers and a dot, it will not allow letters. It is convenient as you don’t have to code any checkings.

For the TextView gravity attribute is specified. It defines how will the text in the TextView will be located. Don’t confuse it with layout_gravity which is responsible for TextView location in a ViewGroup.

Now we need to read field contents, define which buttons has been pressed and output the needed result. Open MainActivity.java and write the code:

I guess everything is clear in comments. Read values, define the button, perform an operation and output to the text field. Activity is a listener of the clicked buttons.

Save everything and run.


Let’s extend the functionality by making menu with clearing fields and exit items. Items will be named Reset and Quit.

Add two constants – these will be IDs of the menu items.

And write code for menu creation and processing:

Save everything and run. Two menu items appeared:

Reset – clears all the fields
Quit – closes the application

As your homework you can implement division by zero checking. And output a message using Toast or right into the result field.



Share this Post :

No comments yet.

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *