먼지나는 블로그

BMI 계산기 구현 본문

내맘대로 공부/kotlin

BMI 계산기 구현

고먼지 2021. 7. 10. 04:29

LinearLayout : 컴포넌트들이 순차적으로 쌓이는 레이아웃 ( 아래 예시는 vertical로 되어있어 세로로 쌓이게 됨)

LinearLayout 화면

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:text="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <TextView
        android:text="2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <TextView
        android:text="3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


</LinearLayout>

BMI 계산기 화면 디자인 xml

dp : 화면이 가지는 사이즈의 기본단위. 안드로이드 스마트폰의 경우 크기가 제각각이기 때문에 사용됨

sp : dp값과는 달리 핸드폰 자체 폰트크기 속성에 따라 크기가 적용됨 ( 폰트를 고정하고 싶은 경우 dp 사용)

 

colors.xml
string.xml

-> text의 속성값을 지정할 때 res > values > colors.xml 파일에서 자신이 원하는 색상이나 문자를 추가해서 사용

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/height"
        android:textColor="@color/custom_black"
        android:textSize="20sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/heightEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:inputType="number" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="@string/weight"
        android:textColor="@color/custom_black"
        android:textSize="20sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/weightEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:ems="10"
        android:inputType="number" />

    <Button
        android:id="@+id/resultButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="@string/done" />

</LinearLayout>

setContentView(R.layout.xml파일이름) -> 해당 xml파일을 액티비티의 ContentView로 설정함 

Log.d(tag, msg) -> 해당 함수의 실행여부에 대한 log검사

 

mainActivity.kt

package com.example.kotlinstudy

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val heightEditText: EditText = findViewById(R.id.heightEditText)
        val weightEditText = findViewById<EditText>(R.id.weightEditText) // 어떤 타입인지를 선언해주지 않을 경우 에러가 뜨게됨 따라서 <>안에 타입을 명시해줘야함

        val resultButton = findViewById<Button>(R.id.resultButton)

        resultButton.setOnClickListener {
            Log.d("MainActivity", "Result Button이 클릭되었습니다")

            if (heightEditText.text.isEmpty() || weightEditText.text.isEmpty()) {
                Toast.makeText(this, "빈 값이 있습니다", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 이 아래로는 절대 빈 값이 올 수 없음.

            val height: Int = heightEditText.text.toString().toInt()
            val weight: Int = weightEditText.text.toString().toInt()
            
            val intent =  Intent(this, ResultActivity::class.java )
            startActivity(intent) // ResultActivity가 다음 화면으로 올라오게 됨
        }
    }
}

intent 참고 : https://developer.android.com/guide/components/intents-filters?hl=ko 

 

인텐트 및 인텐트 필터  |  Android 개발자  |  Android Developers

An Intent is a messaging object you can use to request an action from another app component . Although intents facilitate communication between components in several ways, there are three fundamental use cases: An Activity represents a single screen in…

developer.android.com

이때 새로 추가한 ResultActivity는 AndroidManifest.xml에 추가필수 -> <activity android:name=".ResultActivity"/>

 

 

resultActivity.kt

package com.example.kotlinstudy

import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.pow

class ResultActivity: AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result)

        val height = intent.getIntExtra("height", 0)
        val weight = intent.getIntExtra("weight", 0)

        Log.d("ResultActivity", "height:$height , weight:$weight")

        val bmi = weight / (height / 100.0).pow(2.0)
        val resultText  = when {
            bmi >= 35.0 -> "고도 비만"
            bmi >= 30.0 -> "중정도 비만"
            bmi >= 25.0 -> "경도 비만"
            bmi >= 23.0 -> "과체중"
            bmi >= 18.5 -> "정상체중"
            else -> "저체중"
        }

        val resultValueTextView = findViewById<TextView>(R.id.bmiResultTextView)
        val resultStringTextView = findViewById<TextView>(R.id.resultTextView)

        resultValueTextView.text = bmi.toString()
        resultStringTextView.text = resultText
    }
}

 

Activity_result.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:gravity="center"
    android:orientation="vertical">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="BMI : " />

        <TextView
            android:id="@+id/bmiResultTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:text="23.111111" />
    </LinearLayout>

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="결과는 " />

        <TextView
            android:id="@+id/resultTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:text="과체중입니다" />
    </LinearLayout>
</LinearLayout>

'내맘대로 공부 > kotlin' 카테고리의 다른 글

kotlin firebase 설정 및 로그인 구현  (0) 2021.07.15
Kotlin Collection 개념  (0) 2021.07.11
Kotlin 개발 vs Java 개발  (0) 2021.07.05
kotlin 문법 훑어보기 (+추가)  (1) 2021.07.05