The following code is a simple Android Calculator that I have converted from the work I did for the above online class. It was my starting point into android and it’s simple enough as it’s just one activity.

Create a new Android Application Project. Let’s say your Application Name is “Calculator”, your Project Name is “Calculator”, and your Package Name is “com.example.calculator”. Setup the project with the default settings. Now replace MainActivity.java, activity_main.xml (in res/layout), & strings.xml (in res/values) with the code below. Next, create a new class “CalculatorBrain” and replace CalculatorBrain.java with the code below. Finally, create a new xml file “activity_main” (in res/layout-land) (yes, you will have to create the folder too.) and replace activity_main.xml (in res/layout-land) with the code below. Make sure your package names are changed from “com.himebaugh.calculator” to “com.example.calculator” (or whatever your package is).

The calculator should run without errors! When you rotate the android device, the screen will change to display additional keys for operations like cosine and square root.

Download this Free Calculator App from the Google Play Store
@ https://play.google.com/store/apps/details?id=com.himebaugh.calculator

Subscribe

Comments (14)

Just wanted to say that this was a great tutorial. It had some code errors when I tried to compile it with the newer libraries, but still works well, and is a great basis for starting a more complex calculator. Thanks for sharing.

I think this is an excellent tutorial, good code and well commented so I can understand what’s going on. I only have one small issue with the portrait layout file which I only discovered after adding some custom styles to the buttons and that is that rows 5 and 6 are slightly misaligned with the rest of the layout i.e. buttons 0, 1, 2, 3, the decimal point and the = button.

Not a big deal I know but after spotting it in the styled version of the layout, I reverted to the original code and the misalignment is still there, although more difficult to spot.

I’m guessing that this is to do with the fact that row 6 spans 2 rows to accommodate the double sized 0 and = buttons but I’m unable to resolve this (yet).

thanks you sir I find this project very helpful. However I have this error. Somehow the java code that contains the codes when square root is clicked shows an error. I had to comment them to run the app. Either way it is still very helpful. Thank you sir.

It is indeed working so kudos to you sir! However, I see there is a problem if you get a giant number as a result. It won’t fit in textview in its entirety so the solution would be to convert big number results into decimal numbers with exponent. Do you know how to do that?