This post describes how to create a calculator application especially to help in competitive coding for android devices. The apk created can be used to install the application on different devices. The project has been designed for entry level android programmers.
The Calculator Application
- The calculator can handle arbitrary large numbers
- Arithmetic operations implemented : +,-,*,/
- Boolean operations implemented : and, or, not, xor
- Primality check, finding mod, exponent, GCD operations has also been implemented
- The interface of our calculator application will consist of a grid layout that will contain all the buttons. The button consists of 10 number buttons (0-9), buttons for arithmetics, boolean and miscellaneous operations. There are some more widgets to display text that are known as TextView in android. We have five TextView , two to show input text, one to show operation selected and one for result. The one left widget is used to display some permanent information, in this case it's my name.
- The layouts reside in res/layout folder and are defined in xml format. So, create an activity_main.xml layout file is res/layout directory and copy the code below. If you are using Android Studio activity_main.xml will be created automatically when you create a new project.
- Activity_main.xml : This code creates a user interface for the user to interact with in an XML file. LinearLayout and RelativeLayout are used to arrange these widgets (say button) in a hierarchy. In relative layout you can arrange the children with positions related to each other whereas linear layout arranges them in a linear fashion.
- MainActivity.java: Open mainactivity.java (this file is also created automatically) and copy the following code in it. Here the MainActivity sets the above XML file as it's the corresponding interface and also handles interactions on that user interface, specifically the button clicks. Here is the code that goes into MainActivity.java file.
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <scale android:fromXScale="1.0" android:toXScale="2.0" android:fromYScale="1.0" android:toYScale="2.0" android:duration="50" android:pivotY="50%" android:pivotX="50%" android:repeatCount="1" android:repeatMode="reverse"/> </set>That's it, you are set to go. You can run the project in an emulator by clicking the Run button or you can install the generated apk and run it in a physical android device. The project will run perfectly in 5 inch screen (1280*720 resolution is perfect). Here are some screenshot obtained from running the app in Yu Yuphoria. Output: