HomeTutorialsBasic Calculator Android Kotlin Projects

Basic Calculator Android Kotlin Projects

Are you an aspiring Android developer looking to enhance your skills and build practical projects? If so, then creating a calculator app is an excellent starting point. In this article, we will explore the world of calculator Android Kotlin projects, guiding you through the process of building your own calculator app step by step.

Introduction

The calculator app is a fundamental tool that allows users to perform various mathematical operations conveniently. By creating a calculator app, you can learn key concepts of Android development, such as user interface design, event handling, and data manipulation. Additionally, it provides a solid foundation for more complex projects.

Handling User Inputs

To make your calculator app functional, you need to handle user inputs correctly. Follow these steps to capture user interactions:

  1. Set Button Click Listeners: Attach click listeners to the calculator buttons to capture button presses.
  2. Handle Numeric Inputs: Implement logic to append numeric inputs to the display and update the UI accordingly.
  3. Manage Operator Inputs: Capture operator inputs and store the current input for later calculations.
  4. Respond to Special Inputs: Handle special inputs like the decimal point, clear button, and equal sign to perform appropriate actions.

Implementing Calculator Logic

Now it’s time to implement the core calculator logic. This involves processing the user inputs and performing mathematical operations. Here’s how you can achieve it:

  1. Create a Calculation Engine: Develop a calculation engine that can handle basic arithmetic operations such as addition, subtraction, multiplication, and division.
  2. Store and Retrieve Numbers: Implement a mechanism to store the numbers entered by the user and retrieve them for calculations.
  3. Perform Calculations: Apply the selected operator on the stored numbers and display the result to the user.
  4. Handle Edge Cases: Consider scenarios such as dividing by zero, handling negative numbers, and managing long calculations.

Adding Advanced Features

To make your calculator app stand out, you can incorporate advanced features that enhance the user experience. Here are a few ideas:

  1. Scientific Calculator Functions: Implement advanced mathematical functions like square root, exponentiation, trigonometric functions, and logarithms.
  2. Memory Functionality: Add memory storage and recall features to store values for later use.
  3. Unit Conversion: Include unit conversion capabilities, such as converting between different measurement systems or currencies.

Polishing the User Interface

A visually appealing and user-friendly interface can significantly enhance the overall user experience. Consider the following tips to polish your calculator app’s user interface:

  1. Use Appropriate Colors: Choose colors that are visually pleasing and harmonize well together. Consider using color palettes that are easy on the eyes.
  2. Optimize Layout: Ensure that the UI elements are properly aligned, spaced, and sized for optimal readability and interaction.
  3. Add Animations: Implement subtle animations to make the UI elements more engaging and responsive.
  4. Test Accessibility: Ensure that your app meets accessibility guidelines, including proper contrast, text size, and support for screen readers.

Here is the Code For “Calculator Android Kotlin”

MainActivity.kt

package com.example.calculator

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    // Variable to store the current operand
    private var currentOperand: Double = 0.0
    // Variable to store the current operator
    private var currentOperator: String = ""
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // Set click listeners for number buttons
        btn0.setOnClickListener { numberClick("0") }
        btn1.setOnClickListener { numberClick("1") }
        btn2.setOnClickListener { numberClick("2") }
        btn3.setOnClickListener { numberClick("3") }
        btn4.setOnClickListener { numberClick("4") }
        btn5.setOnClickListener { numberClick("5") }
        btn6.setOnClickListener { numberClick("6") }
        btn7.setOnClickListener { numberClick("7") }
        btn8.setOnClickListener { numberClick("8") }
        btn9.setOnClickListener { numberClick("9") }
        
        // Set click listeners for operator buttons
        btnPlus.setOnClickListener { operatorClick("+") }
        btnMinus.setOnClickListener { operatorClick("-") }
        btnMultiply.setOnClickListener { operatorClick("*") }
        btnDivide.setOnClickListener { operatorClick("/") }
        
        // Set click listener for equals button
        btnEquals.setOnClickListener { calculateResult() }
        
        // Set click listener for clear button
        btnClear.setOnClickListener { clearCalculator() }
    }
    
    // Function to handle number button clicks
    private fun numberClick(number: String) {
        val currentText = txtResult.text.toString()
        txtResult.text = currentText + number
    }
    
    // Function to handle operator button clicks
    private fun operatorClick(operator: String) {
        currentOperator = operator
        currentOperand = txtResult.text.toString().toDouble()
        txtResult.text = ""
    }
    
    // Function to calculate and display the result
    private fun calculateResult() {
        val operand2 = txtResult.text.toString().toDouble()
        var result = 0.0
        
        when (currentOperator) {
            "+" -> result = currentOperand + operand2
            "-" -> result = currentOperand - operand2
            "*" -> result = currentOperand * operand2
            "/" -> result = currentOperand / operand2
        }
        
        txtResult.text = result.toString()
    }
    
    // Function to clear the calculator
    private fun clearCalculator() {
        txtResult.text = ""
        currentOperand = 0.0
        currentOperator = ""
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:textSize="30sp"
        tools:text="0" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn7"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="7" />

        <Button
            android:id="@+id/btn8"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="8" />

        <Button
            android:id="@+id/btn9"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="9" />

        <Button
            android:id="@+id/btnDivide"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="/" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="4" />

        <Button
            android:id="@+id/btn5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="5" />

        <Button
            android:id="@+id/btn6"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="6" />

        <Button
            android:id="@+id/btnMultiply"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="*" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="1" />

        <Button
            android:id="@+id/btn2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="2" />

        <Button
            android:id="@+id/btn3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="3" />

        <Button
            android:id="@+id/btnMinus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="-" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn0"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="0" />

        <Button
            android:id="@+id/btnClear"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="C" />

        <Button
            android:id="@+id/btnEquals"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="=" />

        <Button
            android:id="@+id/btnPlus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="+" />

    </LinearLayout>

</LinearLayout>

Related Articles

Latest news

Unveiling the Darkest Elements in Hogwarts Legacy: Top 10 Elements

Hogwarts Legacy (Buy Now) is a jewel of a game for all the Harry Potter fanbase, inviting them to experience the magical universe of...

Dead Island 2 Cable Guy’s Van Keys location

As you embark on your journey in Dead Island 2, you'll stumble upon a mysterious vehicle known as the Cable Guy Van. This van...

iotty Smart Switch – Complete Review

The smart home industry is rapidly evolving with a plethora of innovative devices vying for consumers' attention. Among these, the iotty Smart Switch stands...

How To Fix Snapchat Support Code SS06

Every Snapchat user cherishes the joy of sharing moments, using filters, and connecting with friends. However, this joy can be interrupted by various glitches...

Can You Refund Fortnite Accounts?

Fortnite, the battle royale game developed by Epic Games, has taken the gaming world by storm since its inception. With its captivating gameplay, interactive...

Stay in the Loop

Get the weekly email from Android Hire that makes reading the news actually enjoyable. Join our mailing list to stay in the loop to stay informed, for free.