상세 컨텐츠

본문 제목

BMI 계산기 안드로이드 앱 토이프로젝트

android

by 개복신 개발자 2022. 2. 8. 14:16

본문

728x90
반응형

-res>layout>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"
    tools:context=".MainActivity">

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

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="체중" />

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

    <Button
        android:text="확인하기"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

-LinearLayout을 통해 순차적인 배열로 구성하고자 하였음

android:orientation = "vertical"이기에 수직으로 항목들이 구성됨

 

-TextViewe는 말 그대로 글자를 넣음

android:text="신장/체중"

 

-EditText 는 값을 넣을 수 있는 블럭

inputType을 지정할 수 있다

 


<?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:textStyle="bold"
        android:textSize="20sp"
        android:text="@string/height"
        android:textColor="@color/custon_black"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

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

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

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

    <Button
        android:textSize="20sp"
        android:layout_marginTop="50dp"
        android:text="확인하기"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

-padding은 안쪽의 간격을 두는 것이고

margin은 해당 블럭을 기준으로 밖에 간격을 두는 것이다

 

-textstyle과 textsize 등으로 텍스트의 모습을 변경한다

-colors.xml에 해당 색을 저장해서 가져올 수 있다

가독성과 추후의 코드 수정을 용이하게 하기 위해 써야 하는 기능

String.xml또한 이름을 등록해놓는 기능으로 생각하면 된다

<color name="custon_black">#222222</color>
<string name="height">신장</string>
<string name="weight">체중</string>

이런식으로 저장

android:textColor="@color/custon_black"

main xml에서는 위와 같이 코드를 작성하여 사용한다


main-xml을 정렬하자

windows ctrl+alt+L

mac option+command+L

 

package fastcampus.aop.part2.aop_part2_chapter01

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

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        setContentView(R.layout.activity_main)
        //R.layout.activity_main 화면을 가져와 contentview로 설정하겠다는 의미
        //R=Resource R.주소를 이용해서 더 간편하게 주소값 대신

        val heightEditText: EditText = findViewById(R.id.heightEditText)
        val weightEditText = findViewById<EditText>(R.id.weightEditText)

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

    }
}

-R.id.id명을 통해 해당 변수를 지정한다

findviewById함수를 이용한다.

 

-oncreate 함수는 자바의 main함수의 의미와 비슷하다

 

-변수 타입을 지정해야됨! EditText, Button등등

 

-주소값을 다 외우는 것은 컴퓨터가 편한 방법

우리가 코딩하기 위해서는 R을 이용해 id를 가져와서 사용하는 것이다!


resultButton.setOnClickListener //listener:듣는 것 클릭이 일어나는 것을 듣는 것
	{
        Log.d("MainActivity","ResultButton이 클릭되었습니다")

        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)

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



    } 

}

-resultButton.setOnclickListener

클릭 되었음을 감지했을 때 실행되는 함수

 

-Log.d

디버깅 로그에서 상태를 표시함

 

-EditText의 값을 가져오기 위한 코드

val height: Int = heightEditText.text는 EditText상태로 넘어온다

따라서 이를 String으로 바꾸고나서 Int형을 변환해야 함

toString().toInt()

 

-만약 빈 값을 보낸다면?

if문을 통해 예외처리

Toast.makeText(this,"빈 값이 있습니다.", Toast.LENGTH_SHORT).show()
return@setOnClickListener

Toast를 통해 알림 처리

context(this)를 넣고 text(빈 값~)을 작성하여 보냄

show()함수가 있어야 화면에 보여짐

 

-return @setOnClickListener

을 통해 setOnClickListener함수를 빠져나갈 것임

그냥 return만 치면 안됨

 

-결과 화면으로 넘어가는 처리하기

val intent = Intent(this, resultActivity::class.java)
startActivity(intent)

intent를 통해 this 화면에서 resultActivity로 넘어가도록 한다.

startActivity(intent)로 실행

 

-레이아웃과 액티비티 파일 생성

 

package fastcampus.aop.part2.aop_part2_chapter01

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class resultActivity: AppCompatActivity(){

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

-resultActivity.kt 생성

 

manifests&gt;AndroidManifest.xml

-manifests에 해당 액티비티를 추가해야 오류 안뜸

application 안에 .resultActivity추가하여 오류 해결

 

모든 과정을 완료하면 확인 버튼 클릭시 result 화면으로 넘어감


 val intent = Intent(this, resultActivity::class.java)

            intent.putExtra("height", height)
            intent.putExtra("weight", weight)

            startActivity(intent)

-intent에 height와 weight 인자를 resultactivity로 넘겨야 함

따라서 위의 코드로 추가한 후 StartActivity 코드를 작성한다.

 

package fastcampus.aop.part2.aop_part2_chapter01

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 >= 20.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
    }
}

-getIntExtra로 인자를 받아옴

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

(이름, 초기값)

 

-when 문 사용하여 비만도 도출

 

<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 : "
        android:textColor="@color/custon_black"
        android:textSize="30dp" />

    <TextView
        android:id="@+id/bmiResultTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="333333333"
        android:textColor="@color/custon_black"
        android:textSize="30dp" />
</LinearLayout>

-textView id 작성

bmiResultTextView

이 id로 결과값을 화면에 띄울 수 있다.

 

resultActivity.kt

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

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

-val resultValueTextView, val resultStringTextView로 해당 TextView를 할당한다

그 후 위에서 얻은 bmi 수치와 그에 따른 비만도 값을 넘긴다

 

-result~~.text ->String 형태로!

 

반응형

'android' 카테고리의 다른 글

비밀 다이어리 토이 프로젝트  (0) 2022.02.16
로또 번호 추첨 토이 프로젝트  (0) 2022.02.09
kotlin 2강  (0) 2022.02.07
kotlin 1강 정리  (0) 2022.02.04
단말기 테스트  (0) 2021.09.06

관련글 더보기

댓글 영역