Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication, or division depending upon the user input. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Pre-requisites:
To Create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio .
Note that select Java as the programming language.
buildFeatures
dataBinding = true
>
Navigate to the app > res > layout > activity_main.xml and add the below code to that file.
Below is the code for the activity_main.xml file:
acitivity_main.xmlOpen the MainActivity.java file there within the class, and make a method named doSum(View v). In this method, first of all, we have to link two EditText with variables so that we can use them for our input. So link those edit box with variables we have written
"EditText e1=(EditText )findViewById(R.id.num1);"
Here num1 is id for the textbox and we are just giving a variable name ‘e1’ to text box with id ‘num1’. Similarly, we have to use the same statement for the second textbox with the variable name ‘e2’. For the third text box, we have used
"TextView t1=(TextView) findViewById(R.id.result);"
Here we have used TextView because we only have to display text avoiding it being user-changeable. Now we have to input numbers in form of string using the getText() function. The input statement will be
"String s11=e1.getText().toString();"
Here s11 stores the number entered in textbox 1. We have to do the same with another Textbox(e2). Now store the number in int form and apply addition. store the added value in another variable. To display stored in sum we have to use setText() as follows:
result.setText(final_sum.toString())
final_sum stores the sum and it’s necessary to convert it to string(.toString()).