How to Build a Simple Calculator App Using Android Studio (Java)
Creating a calculator app is a great beginner-friendly project to get hands-on experience with Android app development. In this guide, we will walk through the steps to build a basic calculator that performs simple arithmetic operations like addition, subtraction, multiplication, and division.
We will be using Java as the programming language and Android Studio as the development environment.
Features of the Calculator App
- Perform basic operations: Addition (+), Subtraction (−), Multiplication (×), Division (÷)
- Support for decimal numbers
- Includes Clear (C) and Equal (=) buttons
- Handles division by zero
Step-by-Step Implementation
Step 1: Create a New Project
- Open Android Studio.
- Click on “Start a new Android Studio project”.
- Choose “Empty Activity”.
- Name your project (e.g., SimpleCalculator).
- Select Java as the programming language.
- Click Finish to create your project
Directory Structure
Once the project is set up, your basic directory structure will look like this:
Step 2: Design the UI in activity_main.xml
Navigate to res > layout > activity_main.xml. Replace the content with the following code to create the UI:
Step 3: Add Logic in MainActivity.java
Code Explanation
- Number Buttons: Append the digit to the input EditText.
- Operator Buttons: Save the first number (num1), set the selected operator, and clear the input.
- Dot Button: Adds a decimal point if it’s not already present.
- Equal Button: Parses the second number (num2), performs the operation, and displays the result.
- Clear Button: Resets the input field and result display.
Conclusion
With just a few lines of code, you now have a fully functional calculator app! This app lays the foundation for learning about UI components, event handling, and simple logic in Android development.
Want to upgrade? Add advanced features like:
- Scientific operations (sin, cos, tan)
- Expression evaluation
- Better UI/UX with themes