• Soubhagyajit Borah • September 9, 2023
In this tutorial, we will guide you through the process of creating a basic calculator app for Android using the Kotlin programming language and Android Studio. By the end of this tutorial, you will have a functional calculator app that can perform basic arithmetic operations.
Prerequisites:
- Android Studio installed on your computer.
- Basic knowledge of Kotlin programming.
Step 1: Create a New Android Project
1. Open Android Studio and click on "Start a new Android Studio project" or select "File" > "New" > "New Project."
2. Choose an appropriate project template (e.g., "Empty Activity" or "Basic Activity") and click "Next."
3. Configure your project by providing a name, package name, and other details. Click "Finish" to create the project.
Step 2: Design the Calculator Layout
1. In the "res" folder of your project, navigate to "layout" and open the "activity_main.xml" layout file.
2. Design your calculator interface by adding buttons for numbers (0-9), arithmetic operators (+, -, *, /), a clear button (C), an equals button (=), and a TextView to display input and results.
Here's a sample layout XML that you can use as a reference:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#4d4d4d" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:orientation="vertical" android:paddingVertical="50dp"> <TextView android:id="@+id/tvOldInput" android:layout_width="match_parent" android:layout_height="50dp" android:layout_gravity="center" android:gravity="right|center_vertical" android:paddingHorizontal="30dp" android:text="" android:textColor="@color/green" android:textSize="25dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tvCurrentOperand" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:gravity="center_vertical|left" android:paddingLeft="50dp" android:text="" android:textSize="30dp" /> <TextView android:id="@+id/tvInput" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_gravity="center" android:gravity="right|center_vertical" android:paddingHorizontal="30dp" android:text="0" android:textColor="@color/white" android:textSize="40dp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <Button android:id="@+id/allClear" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="AC" android:textSize="20dp" /> <Button android:id="@+id/clear" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="C" android:textSize="20dp" /> <ImageButton android:id="@+id/btnBackspace" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center" android:layout_weight="5" android:background="#4d4d4d" android:src="@drawable/img_backspace" /> <Button android:id="@+id/btnDivide" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="÷" android:textColor="@color/green" android:textSize="30dp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <Button android:id="@+id/btnSeven" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="7" android:textSize="20dp" /> <Button android:id="@+id/btnEight" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="8" android:textSize="20dp" /> <Button android:id="@+id/btnNine" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="9" android:textSize="20dp" /> <Button android:id="@+id/btnMultiply" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="×" android:textColor="@color/green" android:textSize="30dp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <Button android:id="@+id/btnFour" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="4" android:textSize="20dp" /> <Button android:id="@+id/btnFive" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="5" android:textSize="20dp" /> <Button android:id="@+id/btnSix" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="6" android:textSize="20dp" /> <Button android:id="@+id/btnMinus" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="-" android:textColor="@color/green" android:textSize="30dp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <Button android:id="@+id/btnOne" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="1" android:textSize="20dp" /> <Button android:id="@+id/btnTwo" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="2" android:textSize="20dp" /> <Button android:id="@+id/btnThree" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="3" android:textSize="20dp" /> <Button android:id="@+id/btnPLus" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="+" android:textColor="@color/green" android:textSize="30dp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <Button android:id="@+id/btnDot" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="." android:textSize="20dp" /> <Button android:id="@+id/btnZero" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:background="#4d4d4d" android:text="0" android:textSize="20dp" /> <Button android:id="@+id/btnEqual" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="8" android:background="@color/orange" android:text="=" android:textSize="20dp" /> </LinearLayout> </LinearLayout>
Note : I know that this is little bit long , but don't worry you can use it as it is. You can Download the all files from Github : Click Here to Download All files
Step 3: Implement the Calculator Logic
1. Open the "MainActivity.kt" file.
2. Define variables for your user interface elements, such as TextView and buttons, at the top of your `MainActivity` class.
// Define variables for UI elementsval tvInput = findViewById<TextView>(R.id.tvInput)val btnOne = findViewById<Button>(R.id.btnOne)val btnTwo = findViewById<Button>(R.id.btnTwo)// Add similar declarations for other buttons// Initialize currentInput as a StringBuildervar currentInput = StringBuilder()
3. Create functions to handle button clicks. For example, functions to append numbers, set operators, calculate results, and clear input.
// Function to append numbers to the current inputprivate fun appendNumber(number: String) { currentInput.append(number) updateDisplay()}// Function to set the current operatorprivate fun setOperator(operator: String) { // Implement logic to set the operator // Update the display to show the current operator}// Function to calculate resultsprivate fun calculateResult() { // Implement arithmetic calculations // Update the display with the result}// Function to clear inputprivate fun clearInput() { // Implement logic to clear the input and reset the display}// Function to update the displayprivate fun updateDisplay() { tvInput.text = currentInput.toString()}
Here's a simple implemention:
package com.example.calculator import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var tvInput: TextView private lateinit var tvOldInput: TextView private var oldValue: String = "" private var newValue: String = "" private var operator: String = "" private var isNewInput: Boolean = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) tvInput = findViewById(R.id.tvInput) tvOldInput = findViewById(R.id.tvOldInput) val btnOne = findViewById<Button>(R.id.btnOne) val btnTwo = findViewById<Button>(R.id.btnTwo) val btnThree = findViewById<Button>(R.id.btnThree) val btnFour = findViewById<Button>(R.id.btnFour) val btnFive = findViewById<Button>(R.id.btnFive) val btnSix = findViewById<Button>(R.id.btnSix) val btnSeven = findViewById<Button>(R.id.btnSeven) val btnEight = findViewById<Button>(R.id.btnEight) val btnNine = findViewById<Button>(R.id.btnNine) val btnZero = findViewById<Button>(R.id.btnZero) val btnDot = findViewById<Button>(R.id.btnDot) val btnPlus = findViewById<Button>(R.id.btnPLus) val btnMinus = findViewById<Button>(R.id.btnMinus) val btnMultiply = findViewById<Button>(R.id.btnMultiply) val btnDivide = findViewById<Button>(R.id.btnDivide) val btnEqual = findViewById<Button>(R.id.btnEqual) val btnClear = findViewById<Button>(R.id.clear) val btnAllClear = findViewById<Button>(R.id.allClear) val numberButtons = listOf( btnOne, btnTwo, btnThree, btnFour, btnFive, btnSix, btnSeven, btnEight, btnNine, btnZero ) numberButtons.forEach { button -> button.setOnClickListener { if (isNewInput) { tvInput.text = "" isNewInput = false } tvInput.append((it as Button).text) } } btnDot.setOnClickListener { if (isNewInput) { tvInput.text = "0." isNewInput = false } else if (!tvInput.text.contains(".")) { tvInput.append(".") } } btnPlus.setOnClickListener { setOperator("+") } btnMinus.setOnClickListener { setOperator("-") } btnMultiply.setOnClickListener { setOperator("*") } btnDivide.setOnClickListener { setOperator("/") } btnClear.setOnClickListener { tvInput.text = "" } btnAllClear.setOnClickListener { tvInput.text = "" tvOldInput.text = "" oldValue = "" newValue = "" operator = "" } btnEqual.setOnClickListener { newValue = tvInput.text.toString() val result = calculate() tvInput.text = result.toString() tvOldInput.text = "" isNewInput = true } } private fun setOperator(op: String) { oldValue = tvInput.text.toString() operator = op tvOldInput.text = "$oldValue $operator" tvInput.text = "" isNewInput = true } private fun calculate(): Double { return when (operator) { "+" -> oldValue.toDouble() + newValue.toDouble() "-" -> oldValue.toDouble() - newValue.toDouble() "*" -> oldValue.toDouble() * newValue.toDouble() "/" -> oldValue.toDouble() / newValue.toDouble() else -> 0.0 } } }
Step 4: Implement Operator and Calculation Logic
1. Extend your code to handle operator buttons (+, -, *, /), the equals button (=), and clear (C).
2. Implement the logic for performing arithmetic operations based on the user's input. You can use a when statement to determine the current operator and perform the calculation accordingly.
// Function to set the current operatorprivate fun setOperator(operator: String) { if (currentInput.isNotEmpty()) { // If input is not empty, set the operator and clear the input currentInput.clear() // Update the display to show the current operator }}// Function to calculate resultsprivate fun calculateResult() { if (currentInput.isNotEmpty()) { val operand2 = currentInput.toString().toDouble() var result = 0.0 // Initialize the result // Determine the current operator and perform the calculation // Update the result // Update the display with the result currentInput.clear() // Clear the input for the next calculation }}// Function to clear inputprivate fun clearInput() { currentInput.clear() // Clear the display}
Step 5: Set Click Listeners
In the "onCreate" method of your "MainActivity", set click listeners for your buttons to call the corresponding functions.
// Set click listeners for number buttonsbtnOne.setOnClickListener { appendNumber("1") }btnTwo.setOnClickListener { appendNumber("2") }// Add click listeners for other number buttons// Set click listeners for operator buttons// Call the setOperator function with the appropriate operator as an argument// Handle equals button clickbtnEqual.setOnClickListener { calculateResult() }// Handle clear button clickclear.setOnClickListener { clearInput() }
Step 6: Test Your Calculator App
1. Run your app on an Android emulator or physical device to test its functionality.
2. Verify that you can input numbers, perform calculations, and clear the input as expected.
3. If you have any question or problems feel free to contact me at Click here to contact or mail me at me@soubhagyajit.com
Conclusion:
Congratulations! You've created a simple calculator app in Android using Kotlin. This tutorial covers the basics of building a calculator user interface and implementing arithmetic operations. You can further enhance your app by adding features like decimal points, handling edge cases, and improving the user interface.
I am currently updating the UI. If you notice any bug please Report it to me.