How to Create a Simple Calculator App on Android Using Kotlin
Creating a basic calculator app is an excellent project for beginners looking
to learn Android programming. By following these steps, you can build a
calculator app using Kotlin in Android Studio. This article includes
additional features, such as Clear
and
Backspace
buttons, as well as improved result formatting to hide
decimals when the result is an integer.
Step 1: Create a New Project in Android Studio
- Open Android Studio, create a new project, and select the Empty Views Activity template.
- Name the project, for example, "CalculatorApp".
-
Choose Kotlin as the programming language, and continue
until the project setup completes.
Step 2: Design the Calculator Interface
Open the activity_main.xml
file in the
res/layout
directory and design a simple calculator interface by
adding the following elements:
- A display to show numbers and results.
- Number buttons from 0-9.
- Operator buttons (+, -, *, /).
-
Special buttons like
Clear (C)
andBackspace (←)
.
Here’s an example XML code to design the interface:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <!-- Display for showing results --> <TextView android:id="@+id/display" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="end" android:padding="16dp" android:text="0" android:textSize="32sp"/> <!-- Clear and Backspace buttons --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingBottom="8dp"> <Button android:text="C" android:onClick="onClearClick" style="@style/CalculatorButton" android:layout_width="0dp" android:layout_weight="1"/> <Button android:text="←" android:onClick="onBackspaceClick" style="@style/CalculatorButton" android:layout_width="0dp" android:layout_weight="1"/> </LinearLayout> <!-- Number and operator buttons --> <GridLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:columnCount="4" android:rowCount="5" android:paddingTop="16dp"> <!-- Row of number and operator buttons --> <Button android:text="7" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="8" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="9" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="/" android:onClick="onOperatorClick" style="@style/CalculatorButton"/> <Button android:text="4" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="5" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="6" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="*" android:onClick="onOperatorClick" style="@style/CalculatorButton"/> <Button android:text="1" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="2" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="3" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="-" android:onClick="onOperatorClick" style="@style/CalculatorButton"/> <Button android:text="0" android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="." android:onClick="onNumberClick" style="@style/CalculatorButton"/> <Button android:text="=" android:onClick="onEqualClick" style="@style/CalculatorButton"/> <Button android:text="+" android:onClick="onOperatorClick" style="@style/CalculatorButton"/> </GridLayout> </LinearLayout>
Step 3: Add Button Styles in styles.xml
To create a consistent style for all buttons, define a custom style in the styles.xml
file:
- Open the
res/values/themes.xml
file. - Add a custom button style named
CalculatorButton
to make the buttons uniform in size, text size, and margin.
Here’s an example of the button style:
<style name="CalculatorButton"> <item name="android:layout_width">70dp</item> <item name="android:layout_height">wrap_content</item> <item name="android:layout_margin">4dp</item> <item name="android:layout_weight">1</item> <item name="android:textSize">24sp</item> </style>
Step 4: Enable View Binding
To use View Binding in your project, update your build.gradle
file (the one in the app
directory) as follows:
- Open
app/build.gradle
. - Inside the
android
block, add the lineviewBinding { enabled = true }
.
Step 5: Implement Logic in MainActivity
After setting up the interface, add calculation logic in the MainActivity.kt
file. This file will handle the calculator's basic operations, manage Clear
and Backspace
buttons, and display results without decimals for integers.
package com.jatisarisolusistudio.calculatorapp import android.os.Bundle import android.view.View import android.widget.Button import androidx.appcompat.app.AppCompatActivity import com.jatisarisolusistudio.calculatorapp.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private var operator: String = "" private var firstNumber: Double? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) } fun onNumberClick(view: View) { val buttonText = (view as Button).text.toString() val displayText = binding.display.text.toString() // Append number or dot if (displayText == "0" && buttonText != ".") { binding.display.text = buttonText } else { binding.display.text = displayText + buttonText } } fun onOperatorClick(view: View) { val buttonText = (view as Button).text.toString() firstNumber = binding.display.text.toString().toDoubleOrNull() operator = buttonText binding.display.text = "0" } fun onEqualClick(view: View) { val secondNumber = binding.display.text.toString().toDoubleOrNull() if (firstNumber != null && secondNumber != null) { val result = when (operator) { "+" -> firstNumber!! + secondNumber "-" -> firstNumber!! - secondNumber "*" -> firstNumber!! * secondNumber "/" -> firstNumber!! / secondNumber else -> 0.0 } binding.display.text = if (result % 1 == 0.0) { result.toInt().toString() // Hasil tanpa desimal jika bilangan bulat } else { result.toString() // Hasil dengan desimal jika bukan bilangan bulat } } } // Clear button handler fun onClearClick(view: View) { binding.display.text = "0" firstNumber = null operator = "" } // Backspace button handler fun onBackspaceClick(view: View) { val displayText = binding.display.text.toString() if (displayText.length > 1) { binding.display.text = displayText.dropLast(1) } else { binding.display.text = "0" } } }
Explanation of Additional Features and Logic
- Display Result without Decimals: The
onEqualClick
function ensures that results are displayed without decimals if the result is an integer. This is done by checking ifresult % 1 == 0.0
. If true, the result is converted to an integer. - Clear Function: The
onClearClick
function resets the display to "0" and clears thefirstNumber
andoperator
values. - Backspace Function: The
onBackspaceClick
function removes the last character on the display. If only one character remains, it resets the display to "0".
Conclusion
By following these steps, you have successfully created a simple calculator app on Android using Kotlin. This app can perform basic operations such as addition, subtraction, multiplication, and division. Additional features like Clear
and Backspace
, along with the automatic integer formatting, make this calculator app practical and user-friendly.
Comments
Post a Comment