Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
How to build a simple Calculator app using Android Studio?
Next article icon

How to Build a Body Mass Index Calculator in Android Studio?

Last Updated : 03 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

The Body Mass Index (BMI) Calculator can be used to calculate BMI values based on height and weight. BMI is a fairly reliable indicator of body fatness for most people.

Formula:

BMI = (weight) / (height * height)

Approach: BMI is a number calculated from an individual’s weight and height. To find out BMI we will take input from the user (both height and weight) which will be stored in height and weight variables for further calculation. The calculation process is simple, we will simply divide weight in kilograms by the square of the height. Now as per the BMI calculated, it will execute the respective if-else statement. We are also checking if the user is pressing submit button without entering the inputs, in that case, we will display a Toast message saying “Please enter the valid height and weight”.  In this article, we will be building Body Mass Index Calculator in Android Studio using Kotlin and XML. 

https://media.geeksforgeeks.org/wp-content/uploads/20210827203204/WhatsApp-Video-2021-08-27-at-8.26.35-PM.mp4

Step by Step Implementation

Step 1: Create a New Project 

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Working with the build.gradle(Module) File

You need to apply the plugin kotlin-android-extensions in app build.gradle module like this

plugins {

   id ‘com.android.application’

   id ‘kotlin-android’

   id ‘kotlin-android-extensions’

}

Step 3: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 
    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:orientation="vertical"
    tools:context=".MainActivity">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:text="Body Mass Index Calculator"
        android:textSize="25sp"
        android:textStyle="bold" />
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        android:text="Weight(in Kg)"
        android:textSize="20dp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.292" />
  
    <EditText
        android:id="@+id/etWeight"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp" />
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        android:text="Height (in cm)"
        android:textSize="20dp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.292" />
  
    <EditText
        android:id="@+id/etHeight"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:textSize="20dp" />
  
    <Button
        android:id="@+id/calculate_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="40dp"
        android:backgroundTint="#2CD3BE"
        android:text="Calculate" />
  
    <TextView
        android:id="@+id/bmi_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:text="The BMI is "
        android:textSize="20dp"
        android:visibility="gone" />
  
    <TextView
        android:id="@+id/bmi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:text="BMI"
        android:textSize="20dp"
        android:visibility="gone" />
  
    <TextView
        android:id="@+id/status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:text="Status"
        android:textSize="20dp"
        android:textStyle="bold"
        android:visibility="gone" />
  
    <Button
        android:id="@+id/ReCalculate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:backgroundTint="#EAA268"
        android:text="Recalculate"
        android:visibility="gone" />
      
</androidx.appcompat.widget.LinearLayoutCompat>
                      
                       

After writing this much code our UI looks like this:

Step 4: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. 

Kotlin

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        calculate_btn.setOnClickListener {
  
            // Check if the height EditText and Weight EditText are not empty
            if (etHeight.text.isNotEmpty() && etWeight.text.isNotEmpty()) {
                val height = (etHeight.text.toString()).toInt()
                val weight = (etWeight.text.toString()).toInt()
  
                // calculateBMI will return BMI
                val BMI = calculateBMI(height, weight)
  
                bmi.text = BMI.toString()
                bmi.visibility = View.VISIBLE
  
                // update the status text as per the bmi conditions
                if (BMI < 18.5) {
                    status.text = "Under Weight"
                } else if (BMI >= 18.5 && BMI < 24.9) {
                    status.text = "Healthy"
                } else if (BMI >= 24.9 && BMI < 30) {
                    status.text = "Overweight"
                } else if (BMI >= 30) {
                    status.text = "Suffering from Obesity"
                }
  
                bmi_tv.visibility = View.VISIBLE
                status.visibility = View.VISIBLE
  
                ReCalculate.visibility = View.VISIBLE
                calculate_btn.visibility = View.GONE
                  
            }
  
            // when either Weight EditText or 
            // height EditText have null value
            // we will display toast.
            else {
                Toast.makeText(this, "please enter the valid height and weight", Toast.LENGTH_SHORT).show()
            }
        }
          
        ReCalculate.setOnClickListener {
            ResetEverything()
        }
  
    }
  
    // Function to reset all Text and EditText fields.
    private fun ResetEverything() {
          
        calculate_btn.visibility = View.VISIBLE
        ReCalculate.visibility = View.GONE
  
        etHeight.text.clear()
        etWeight.text.clear()
        status.text = " "
        bmi.text = " "
        bmi_tv.visibility = View.GONE
    }
  
    // Function for calculating BMI
    private fun calculateBMI(height: Int, weight: Int): Float {
          
        val Height_in_metre = height.toFloat() / 100
        val BMI = weight.toFloat() / (Height_in_metre * Height_in_metre)
  
        return BMI
    }
}
                      
                       

Output:

https://media.geeksforgeeks.org/wp-content/uploads/20210827203204/WhatsApp-Video-2021-08-27-at-8.26.35-PM.mp4


Next Article
How to build a simple Calculator app using Android Studio?
author
nirajgusain5
Improve
Article Tags :
  • Android
  • Kotlin

Similar Reads

  • 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. Prerequisites: Before making this application, you can go through t
    6 min read
  • How to build a simple Calculator app using Android Studio?
    Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication, or division depending upon the user input. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project
    6 min read
  • How to Build a Roman Numeral Convertor in Android Studio?
    Roman Numeral converter is an app through which we can convert a decimal number to its corresponding roman number or a roman number to its corresponding decimal number in the range of 1 to 3999. The user will enter a decimal number and on clicking the convert to roman numeral button, the entered num
    5 min read
  • How to Build a Palindrome Checker App in Android Studio?
    In this article, we will be building a Palindrome Checker android app in Android Studio using Java/Kotlin and XML. The app will check whether the entered word is Palindrome or not, if the entered word is a Palindrome then a toast will be displayed having the message "Yes, it's a palindrome" otherwis
    3 min read
  • How to Build a Prime Number Checker Android App in Android Studio?
    A prime number is a natural number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 ….. . In this article, we will be building a Prime Number Checker android app in Android Studio using Kotlin and XML. The app will check whether the entere
    3 min read
  • How to Build a Simple Expense Calculator App in Android?
    Pre-requisites: Android App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioHow to Create/Start a New Project in Android Studio?Running your first Android appRecyclerView in Android with ExampleShared Preferences in Android with Example A simple expense calculator let
    10 min read
  • How to Build a Number Shapes Android App in Android Studio?
    Android is a vast field to learn and explore and to make this learning journey more interesting and productive we should keep trying new problems with new logic. So, today we are going to develop an application in android studio which tells us about Numbers that have shapes. We will be covering two
    4 min read
  • How to Build a Step Counting Application in Android Studio?
    Many of us have used the step counter on our phones while we go for walk or run. It counts the total steps that the user has walked and displays it on the screen. The other name for the step counter is a pedometer. But have you ever thought about how can an app count our steps? What is the coding be
    7 min read
  • How to Create Interfaces in Android Studio?
    Interfaces are a collection of constants, methods(abstract, static, and default), and nested types. All the methods of the interface need to be defined in the class. The interface is like a Class. The interface keyword is used to declare an interface. public interface AdapterCallBackListener { void
    4 min read
  • How to Build a Temperature Converter App in Android?
    Temperature Converter Application is built using android studio where temperature entered in Celsius can be converted to Fahrenheit. The output will be displayed on Snackbar. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to impleme
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences