[패캠 안드로이드] Part2 Ch1.2 ~ Ch 1.5 BMI 계산기

0
post-thumbnail

Part2 Ch1.2 ~ Ch 1.5 BMI 계산기

  • 주석 단축키: Ctrl+/
  • Reformat Code 단축키: Ctrl + Alt + L

activity_main.xml


<!--LinearLayout: orientation 설정 필수-->
<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">

    <!--margin: component 밖에 여백을 만듦-->
    <!--padding: component 안에 content의 크기를 줄여서 여백을 만듦-->

    <!--주석 단축키: Ctrl+/ -->
    <!--Reformat Code 단축키: Ctrl + Alt + L-->

    <!--TextView: 화면에 Text 표시-->
    <!--text: res 폴더-> strings -> yourHeight 문자열 지정-->
    <!--textColor: res 폴더-> values -> colors -> myPink 색 지정-->
    <!--textSize: sp 단위를 사용할 경우(권장) 사용자가 핸드폰 글씨 크기 설정을 변경할 때 함께 적용된다-->
    <!--textSize: dp 단위를 사용할 경우 사용자가 핸드폰 글씨 크기 설정과 무관하다-->
       <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/yourHeight"
        android:textColor="@color/myPink"
        android:textSize="20sp"
        android:textStyle="bold" />

    <!--EditText: 사용자로부터 입력받을 때 사용-->
    <!--inputType: 입력 시 나타나는 키보드 종류(한/영/숫자) 설정-->
    <!--number: 정수, numberSigned: 부호있는 정수, numberDecimal: 실수-->
    <EditText
        android:id="@+id/heightEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:inputType="numberDecimal" />

    <!--text: res 폴더-> strings -> yourWeight 문자열 지정-->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="@string/yourWeight"
        android:textColor="@color/myPink"
        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:inputType="numberDecimal" />

    <Button
        android:id="@+id/okButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:backgroundTint="@color/myPink"
        android:text="확인" />


</LinearLayout>

MainActivity.kt

package fastcampus.aop.part2.chapter01

//import 단축키: Alt + Enter
import android.content.Intent
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)

        //R.layout.activity_main 의 레이아웃을 이 Content의 View로 사용
        setContentView(R.layout.activity_main)

        // public <T extends android.view.View> T findViewById(@IdRes int id)
        // Params: id – the ID to search for
        // Returns: a view with given ID if found, or null otherwise

        val heightEditText: EditText = findViewById(R.id.heightEditText) //val 타입 명시한 경우
        val weightEditText = findViewById<EditText>(R.id.weightEditText) //val 타입 명시하지 않은 경우
        val okButton: Button = findViewById(R.id.okButton)

        okButton.setOnClickListener {
            //Logcat 창 -> Emulator, Process 선택 -> Debug Log 확인 가능
            Log.d("MainActivity", "okButton이 클릭되었습니다")

            //height 빈 값인 경우 예외 처리
            if(heightEditText.text.isEmpty()) {
                Log.d("MainActivity", "Empty height")
                Toast.makeText(this, "신장을 입력해주세요!", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            //weight 빈 값인 경우 예외 처리
            if(weightEditText.text.isEmpty()){
                Log.d("MainActivity", "Empty weight")
                Toast.makeText(this, "체중을 입력해주세요!", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            val height : Double = heightEditText.text.toString().toDouble()
            val weight : Double = weightEditText.text.toString().toDouble()

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

            //MainActivity 에서 ResultActivity 불러오기 위해서 인텐트(Intent) 사용
            val intent = Intent (this,ResultActivity::class.java )

            //인텐트에 값 저장하기
            intent.putExtra("height", height)
            intent.putExtra("weight", weight)

            startActivity(intent)
        }

    }
}

Toast

  • Toast 메세지가 안뜬다
    context 매개변수에 문제가 있는 것 같은데 아직 해결하지 못했다
  • 해결: AVD Manager -> 가상머신 선택 -> WipeData
Toast.makeText(this, "토스트1", Toast.LENGTH_LONG).show()
Toast.makeText(applicationContext, "토스트2", Toast.LENGTH_LONG).show()
Toast.makeText(this.applicationContext, "토스트3", Toast.LENGTH_LONG).show()

ResultActivity.kt

package fastcampus.aop.part2.chapter01

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

//java 폴더 -> 패키지 우클릭 -> New -> Kotlin Class/File 만들기
//android.content.ActivityNotFoundException 발생
//-> AndroidManifest 파일에 ResultActivity 추가해야

class ResultActivity : AppCompatActivity() {
    //onCreate: ResultActivity가 시작되었을 때 호출되는 함수
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        //res 폴더 -> layout 우클릭 -> New -> Layout resource file 만들기
        //R.layout.activity_result 의 레이아웃을 이 Content의 View로 사용
        setContentView(R.layout.activity_result)

        //인텐트에 저장된 값 불러오기
        //만약 인텐트에 값이 저장되어있지 않은 경우 -> defaultValue 갖는다
        val height = intent.getDoubleExtra("height",0.0)
        val weight = intent.getDoubleExtra("weight",0.0)

        Log.d("ResultActivity", "height: $height, weight: $weight ")
        
        //BMI 계산: 자신의 몸무게를 키의 제곱으로 나누는 것 (kg/m^2)
        //자바에서 제곱근 계산: a^b = Math.pow(double a,double b)
        //코틀린에서 제곱근 계산: a^b = a.pow(double b)
        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 -> "저체중입니다!"
        }

        //구한 값 activity_result 레이아웃으로 넘겨주기
        val bmiResultTextView = findViewById<TextView>(R.id.bmiResultTextView)
        val resultTextView = findViewById<TextView>(R.id.resultTextView)

        bmiResultTextView.text = bmi.toString()
        resultTextView.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:orientation="vertical"
    android:gravity="center">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="나의 BMI지수는? "
            android:textColor="@color/myPink"
            android:textSize="20sp"
            android:textStyle="bold" />
        <!--tools: Design 창에서만 보이고, 실제 앱 실행 화면에는 보이지 않도록 한다-->
        <TextView
            android:id="@+id/bmiResultTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="20sp"
            android:textStyle="bold"
            tools:text="19.0" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="나의 결과는? "
            android:textColor="@color/myPink"
            android:textSize="20sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/resultTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="20sp"
            android:textStyle="bold"
            tools:text="정상 체중입니다!" />
    </LinearLayout>

</LinearLayout>

📌참고 자료

암시적 인텐트가 시스템을 통해 전달되어 다른 액티비티를 시작하는 방법

  • 액티비티 A가 작업 설명이 있는 Intent를 생성,
    이를 startActivity()에 전달
  • Android 시스템이 모든 앱에서 해당 인텐트와 일치하는 인텐트 필터를 검색
  • 일치하는 항목을 찾으면,
    시스템이 해당 액티비티의 onCreate() 메서드를 호출하여 이를 Intent에 전달, 일치하는 액티비티(액티비티 B) 시작
  • 일치하는 항목을 찾지 못하면, android.content.ActivityNotFoundException 발생
profile
Be able to be vulnerable, in search of truth

0개의 댓글