안드로이드 스튜디오/프로젝트

[안드로이드/Kotlin] 분 단위 나이 계산기

코메인 2023. 2. 9. 23:18

안녕하세요~ 코딩하는 코알못 코메인입니다.

코틀린 언어를 공부하고 처음으로 간단한 앱을 하나 제작해 봤다.

 

해당 앱은 분 단위 나이 계산기이고, 내 나이를 분으로 계산하는 앱이다.

예를 들어 내가 2000년 01월 01일에 태어 났으면 2000년 01월 01일 00시부터 오늘 00시까지로 나이를 분으로 계산해주는 것이다.

해당 날짜로 한다면 오늘 날짜인 2023년 02월 09일 기준으로 총 12153600분 살아 온 것이다.

 

제작 스펙은 이렇다.

사용한 언어 : Kotlin

사용한 툴 : AndroidStudio

 

앱을 살펴보자.

실행

 

앱을 실행하면 해당 화면이 나온다.

LinearLayout으로 UI를 배치 했다.

 

날짜 선택을 클릭하면

캘린더가 나오고 날짜를 선택 할 수 있다.

Calendar로 오늘 날짜를 받아오고, 캘린더는 DatePickerDialog 함수를 사용했다.

 

태어난 날을 선택하고 확인을 누르면 선택 날짜에 선택한 날이 출력되고, 밑에 분으로 치환된 시간이 출력된다.

그리고 하단에 짧은 시간 노출되는 메세지가 출력된다.

 

이제 코드를 보자.

코드

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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:background="@color/bgColor"
    android:gravity="center_horizontal"
    android:padding="16dp"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="나이 계산기"
        android:textColor="@color/MainTextColor"
        android:textSize="25sp"
        android:textStyle="bold"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="AGE IN MINUTES"
        android:padding="10dp"
        android:background="@color/MainTextColor"
        android:textColor="@color/bgColor"
        android:textSize="25sp"
        android:textStyle="bold"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="분 단위"
        android:textColor="@color/MainTextColor"
        android:textSize="25sp"
        android:textStyle="bold"/>

    <Button
        android:id="@+id/btnDateSelect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="날짜 선택"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="@color/btnTextColor"
        android:backgroundTint="@color/btnBgColor"
        android:layout_marginTop="16dp"/>

    <TextView
        android:id="@+id/tvSelectedDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="0-0-0"
        android:textColor="@color/MainTextColor"
        android:textSize="20sp"
        android:textStyle="bold"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="선택 날짜"
        android:textColor="@color/lightGray"
        android:textSize="20sp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tvAgeInMinutes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="0"
        android:textColor="@color/MainTextColor"
        android:textSize="35sp"
        android:textStyle="bold"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="분"
        android:textColor="@color/lightGray"
        android:textSize="25sp"
        android:textStyle="bold"/>


</LinearLayout>

 

MainActivity.kt

package com.example.ageminutescalc

import android.app.DatePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {

    private var tvSelectedDate : TextView? = null
    private var tvAgeInMinutes : TextView? = null

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

        val btnDateSelect : Button = findViewById(R.id.btnDateSelect)
        tvSelectedDate = findViewById(R.id.tvSelectedDate)
        tvAgeInMinutes = findViewById(R.id.tvAgeInMinutes)

        btnDateSelect.setOnClickListener {
            clickDateSelect()
        }

    }

    private fun clickDateSelect(){

        val myCalendar = Calendar.getInstance()
        val year = myCalendar.get(Calendar.YEAR)
        val month = myCalendar.get(Calendar.MONTH)
        val day = myCalendar.get(Calendar.DAY_OF_MONTH)

        val dpd = DatePickerDialog(this,
            { view, selectedyear, selectedmonth, selecteddayofMonth ->
                Toast.makeText(this, "${selectedyear}년 ${selectedmonth + 1}월 ${selecteddayofMonth}일", 
                    Toast.LENGTH_SHORT).show()

                val selectedDate = "$selectedyear-${selectedmonth + 1}-$selecteddayofMonth"

                tvSelectedDate?.text = selectedDate

                val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)

                val theDate = sdf.parse(selectedDate)

                theDate?.let {
                    val selectedDateInMinutes = theDate.time / 60000

                    val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))

                    currentDate?.let {
                        val currentDateInMinutes = currentDate.time / 60000
                        
                        val differenceInMinutes = currentDateInMinutes - selectedDateInMinutes

                        tvAgeInMinutes?.text = differenceInMinutes.toString()
                    }
                }

            },
            year,
            month,
            day
        )

        dpd.datePicker.maxDate = System.currentTimeMillis() - 86400000

        dpd.show()

    }
}

 

약간의 설명을 달아둔 코드도 첨부하겠다.

package com.example.ageminutescalc

import android.app.DatePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {

    private var tvSelectedDate : TextView? = null
    private var tvAgeInMinutes : TextView? = null

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

        val btnDateSelect : Button = findViewById(R.id.btnDateSelect)
        tvSelectedDate = findViewById(R.id.tvSelectedDate)
        tvAgeInMinutes = findViewById(R.id.tvAgeInMinutes)

        btnDateSelect.setOnClickListener {
            clickDateSelect()
        }

    }

    private fun clickDateSelect(){

        val myCalendar = Calendar.getInstance()
        val year = myCalendar.get(Calendar.YEAR)
        val month = myCalendar.get(Calendar.MONTH)
        val day = myCalendar.get(Calendar.DAY_OF_MONTH)

        //달력 다이어로그
        val dpd = DatePickerDialog(this,
            { view, selectedyear, selectedmonth, selecteddayofMonth ->
                //month +1은 month를 0~11까지로 값을 읽기 때문에 +1을 해줘야 1~12월로 할 수 있다.
                Toast.makeText(this, "${selectedyear}년 ${selectedmonth + 1}월 ${selecteddayofMonth}일",
                    Toast.LENGTH_SHORT).show()

                val selectedDate = "$selectedyear-${selectedmonth + 1}-$selecteddayofMonth"

                tvSelectedDate?.text = selectedDate

                val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)

                val theDate = sdf.parse(selectedDate)

                //60000으로 나누는 이유는 getTime 함수를 사용할 때 값이 밀리세컨드로 나온다.
                //해당 값을 초 단위로 바꾸기 위해서는 1000을 나누고, 60으로 한번 더 나눠줘야 한다.
                //그리고 time과 getTime은 같은 기능이다.
                theDate?.let {
                    val selectedDateInMinutes = theDate.time / 60000

                    val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))

                    currentDate?.let {
                        val currentDateInMinutes = currentDate.time / 60000

                        //select는 1970년 1월 1일 자정부터 태어날 날 자정까지의 시간
                        //current는 1970년 1월 1일 자정부터 오늘 날까지의 시간
                        val differenceInMinutes = currentDateInMinutes - selectedDateInMinutes

                        tvAgeInMinutes?.text = differenceInMinutes.toString()
                    }
                }

            },
            year,
            month,
            day
        )

        //달력에서 날짜 선택을 전날까지만 가능하게 제한
        //86400000은 하루의 ms 값이다. 86400000의 값을 빼지 않으면 날짜 선택을 오늘까지만 제한 가능
        dpd.datePicker.maxDate = System.currentTimeMillis() - 86400000

        dpd.show()
    }
}

 


이상으로 글을 마치겠습니다.

보시고 궁금하신 것이 있다면, 댓글을 달아주세요. 제가 아는 선에서 최대한 답변드리겠습니다.

오늘도 행복한 하루 되시고, 즐코하세요! 읽어주셔서 감사합니다~