DBILITY

android bmi 본문

android/kotlin

android bmi

DBILITY 2024. 1. 11. 17:50
반응형

연습삼아 해봤다. 지금은..이렇군

build.gradle.kts

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
}

android {
    namespace = "com.dbility.apps.test02"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.dbility.apps.test02"
        minSdk = 24
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildFeatures {
        viewBinding = true
    }
}

dependencies {

    implementation("androidx.core:core-ktx:1.12.0")
    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.11.0")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.5")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Test02"
        tools:targetApi="31"
        >
        <activity
            android:name=".MainActivity"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvCurrentDateTime"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="16dp"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:text="2024년 1월 10 13시 44분 20초" />

    <EditText
        android:id="@+id/txtHeight"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:hint="Height"
        android:inputType="numberDecimal"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/txtWeight"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:hint="Weight"
        android:inputType="numberDecimal"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtHeight" />

    <Button
        android:id="@+id/btnResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="RESULT"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtWeight" />

    <ScrollView
        android:id="@+id/scvHistory"
        android:layout_width="409dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/tvCurrentDateTime"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/btnResult">

        <LinearLayout
            android:id="@+id/resultHistory"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="8dp">

        </LinearLayout>
    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

package com.dbility.apps.test02

import android.content.Context
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.core.widget.TextViewCompat
import com.dbility.apps.test02.databinding.ActivityMainBinding
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.Timer
import kotlin.concurrent.timer
import kotlin.math.pow
import kotlin.math.round

class MainActivity : AppCompatActivity() {

    private val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val inputMethodManager by lazy {
        applicationContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    }

    private val dateFormat by lazy {
        SimpleDateFormat("yyyy년도 MM월 dd일 HH시 mm분 ss초", Locale.getDefault())
    }

    private var timerCurrent: Timer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.btnResult.setOnClickListener {
            if (binding.txtHeight.text.toString().trim().length == 0) {
                Toast.makeText(this, "키를 입력하세요", Toast.LENGTH_LONG).show()
                binding.txtHeight.requestFocus()
            } else if (binding.txtWeight.text.toString().trim().length == 0) {
                Toast.makeText(this, "몸무게를 입력하세요", Toast.LENGTH_LONG).show()
                binding.txtWeight.requestFocus()
            } else {
                inputMethodManager.hideSoftInputFromWindow(binding.root.windowToken, 0)

                var height: Float = binding.txtHeight.text.toString().toFloat()
                var weight: Float = binding.txtWeight.text.toString().toFloat()
                val result: Array<Any> = getBmi(height, weight)
                //Log.i("result", result[0].toString() + "," + result[1].toString())
                var resultView: TextView = TextView(this).apply {
                    text = result[0].toString().plus(" ").plus(result[1].toString()).plus(" - ")
                        .plus(dateFormat.format(Date()))
                }
                TextViewCompat.setTextAppearance(
                    resultView,
                    androidx.constraintlayout.widget.R.style.TextAppearance_AppCompat_Small
                )

                binding.resultHistory.addView(resultView)

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    binding.scvHistory.scrollToDescendant(resultView)
                } else {
                    binding.scvHistory.fullScroll(ScrollView.FOCUS_DOWN)
                }

            }

        }
    }

    override fun onResume() {
        timerCurrent = timer(period = 1000) {
            runOnUiThread {
                binding.tvCurrentDateTime.text = dateFormat.format(Date())
            }
        }
        super.onResume()
    }

    override fun onPause() {
        timerCurrent?.cancel()
        super.onPause()
    }

    private fun getBmi(height: Float, wegiht: Float): Array<Any> {

        var bmi = round((wegiht / (height / 100.0f).pow(2)) * 10.0f) / 10.0f
        var message = ""
        when {
            bmi < 18.5 -> message = "저체중"
            bmi >= 18.5 && bmi < 23 -> message = "정상"
            bmi >= 23 && bmi < 25 -> message = "비만전단계"
            bmi >= 25 && bmi < 30 -> message = "1단계 비만"
            bmi >= 30 && bmi < 35 -> message = "2단계 비만"
            else -> message = "3단계 비만..어쩌니.."
        }

        return arrayOf(bmi, message + "입니다")

    }
}
반응형

'android > kotlin' 카테고리의 다른 글

안드로이드 정리 3  (0) 2024.01.23
안드로이드 정리 2  (0) 2024.01.19
android avd path change ( 경로 변경 )  (0) 2024.01.16
안드로이드 정리 1  (0) 2023.09.15
kotlin fundamental summary ( 기초정리 )  (0) 2023.08.30
Comments