How to Build Age Calculator in Android Studio?
Hello geeks, today we are going to make an application to calculate Age or time period between two dates. By making this application one can calculate his/her exact age, also one can calculate the exact difference between two dates.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Before making this application, you can go through the article Program to calculate age to have a better understanding of the concepts used in this application.
What we are going to build in this article?
In this application, we will be using two DatePickers, where user can select the date no. 1 and 2 respectively. A Button is used to perform the calculation part and show the result in a TextView named as result. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1: Creating a new project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- You can change the name of the project at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2: Navigate to Build scripts > build.gradle(module) file and add the following dependency to it
Step 3: Working with the activity_main.xml file
Here we will design the user interface of our application. We will be using the following components for their respective works:
- Button 1: to pick the first date user wants to enter.
- Button 2: to pick the second date user wants to enter.
- Button 3: to perform the calculation
- TextView: to show the final output(age).
Navigate to the app > res > layout > activity_main.xml and add the below code to that file.
After implementing the above code, the design of the activity_main.xml file looks like this.
Step 4: Working with MainActivity.java file
In MainActivity.java file onClickListerner is used on buttons to pick the date and to perform the calculation. Use the following code in the MainActivity.java file.
Congratulations! we have successfully the application to calculate the age or difference between two dates. Here is the final output of our application.