본문 바로가기
안드로이드/Kotlin

BMI 계산기 - 계산 기능

by step 1 2021. 6. 13.
반응형

코드를 정렬하는 단축키: ctrl + alt + L

 

소스코드 수정

java -> 프로젝트 명 -> MainActivity.kt

 

화면 입력창과 코틀린 소스 변수 연결 시키기

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

//      EditText타입 변수에 각 EditText의 값을 가져온다.
        val heightEditText: EditText = findViewById(R.id.heightEditText)
        val weightEditText = findViewById<EditText>(R.id.weightEditText)

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

 

에러 해결 alt + enter

 

버튼 클릭 이벤트 처리

//      버튼 클릭 이벤트 처리
        resultButton.setOnClickListener {
//          로그 찍기
            Log.d("MainActivity","ResultButton 이 클릭되었습니다.")

//          비어있는 값일 경우 경고창을 띄워주고 종료
            if (heightEditText.text.isEmpty() || weightEditText.text.isEmpty()) {
                Toast.makeText(this,"빈 값이 있습니다.", Toast.LENGTH_SHORT).show()
                /*버튼 클릭 함수를 나온다.*/
                return@setOnClickListener
            }

            //          Int형으로 변환하여 변수에 값 저장
            val height:Int = heightEditText.text.toString().toInt()
            val weight:Int = weightEditText.text.toString().toInt()

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

//          MainActivity에서 ResultActivity 호출 Intent(새로운 액티비티 전 화면, 새로 호출할 화면)
            val intent = Intent(this, ResultActivity::class.java)
            startActivity(intent)
        }

 

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

 

입력후 결과를 보여줄 Activity를 생성(Result Activity.kt, activity_result.xml)

코틀린 소스파일과 layout화면 을 함께 생성한다.

 

 

아래와 같은 에러가 나온다면 manifests에 등록을 해주어야 한다.

 

Unable to find explicit activity class {com.example.aoppart2chapter01/com.example.aoppart2chapter01.ResultActivity}; have you declared this activity in your AndroidManifest.xml?

계속해서 코드 추가

ResultActivity.kt

package com.example.aoppart2chapter01

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)

//      Intent로 전송한 데이터를 받는 방법 (intent 이전 화면에서의 Intent 변수명)
        val height = intent.getIntExtra("height",0)
        val weight = intent.getIntExtra("weight",0)

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

//      pow: 제곱근 함수 사용
        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.0 -> "정상체중"
           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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textSize="30sp"
            android:textColor="@color/custom_black"
            android:text="BMI : "
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>

<!--tools:text="33333333":  툴내에서만 확인용으로 보여주는 명령어 앱을 실행시키면 보이지 않는다.-->
        <TextView
            android:textSize="30sp"
            android:textColor="@color/custom_black"
            tools:text="33333333"
            android:id="@+id/bmiResultTextView"
            android:text=""
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
/>

    </LinearLayout>

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textSize="30sp"
            android:textColor="@color/custom_black"
            android:text="결과는 : "
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
        <TextView
            android:textSize="30sp"
            android:textColor="@color/custom_black"
            android:id="@+id/resultTextView"
            android:text=""
            tools:text="과체중입니다"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>

    </LinearLayout>

</LinearLayout>

 

화면

 

 

 

반응형

'안드로이드 > Kotlin' 카테고리의 다른 글

로또 추첨기 만들기 - 1  (0) 2021.06.20
BMI 계산기 - 레이아웃  (0) 2021.06.13
안드로이드 스튜디오 에러  (0) 2021.06.13
Kotlin 개념, 문법  (0) 2021.06.13