XML - LinearLayout, DatePickerDialog

2024. 4. 9. 17:26IT/Android

728x90

<미리 보기>

스트레스를 유발하는 예제의 끔찍한 UI..

 

 

<소스 코드>

https://github.com/SeongHyunJeon/android-kotlin-practice/tree/edcd0f529e608990163405424f3cb3715af17ed6/DOBCalc

 

 

<정리>

LinearLayout의 속성 orientation을 사용하면 내부의 정렬 방향을 설정할 수 있고, 속성 gracvity를 사용하면 정렬 방법을 설정할 수 있다. 위의 예시에선 orientation을 vertical로 설정하여 뷰 들이 세로로 정렬되었고, gravity를 center_horizontal로 설정하여 수평 가운데 정렬을 설정하였다.

<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:background="@color/bg_color"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:padding="16dp"
    >

//...생략

DatePickerDialog를 통해 괜찮은 캘린더 UI를 출력할 수 있는데, 해당 캘린더에서 선택된 날짜는 두 번째 파라미터 람다의 인자로 전달되어 이를 사용한 연산을 정의할 수 있다. 위의 예시에선 선택된 날짜와 현재 날짜의 차를 시간과 분으로 계산하여 텍스트로 출력 했다. 만약 캘린더에서 선택 날짜의 범위를 제한하고 싶다면 datePicker의 minDate, maxDate 프로퍼티를 사용을 고려하자.

private fun clickDatePicker() {
    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,
        { _, selectedYear, selectedMonth, selectedDayOfMonth ->
            Toast.makeText(this, "You've chosen the date", Toast.LENGTH_SHORT).show()

            val tempSelectedDate = "$selectedYear/${selectedMonth+1}/$selectedDayOfMonth"
            selectedDate!!.text = tempSelectedDate

            val sdf = SimpleDateFormat("yyyy/MM/dd", Locale.KOREA)
            val selectedDateInTimes = sdf.parse(tempSelectedDate)!!.time / (1000 * 60 * 60)
            val currentDateInTimes = sdf.parse(sdf.format(System.currentTimeMillis()))!!.time / (1000 * 60 * 60)
            val differenceOfTimesOfDates = currentDateInTimes - selectedDateInTimes
            ageInTimes!!.text = differenceOfTimesOfDates.toString()

            val selectedDateInMinutes = sdf.parse(tempSelectedDate)!!.time / (1000 * 60)
            val currentDateInMinutes = sdf.parse(sdf.format(System.currentTimeMillis()))!!.time / (1000 * 60)
            val differenceOfMinutesOfDates = currentDateInMinutes - selectedDateInMinutes
            ageInMinutes!!.text = differenceOfMinutesOfDates.toString()
        },
        year,
        month,
        day
    )

    dpd.datePicker.maxDate = System.currentTimeMillis() - ( 1000 * 60 * 60 * 24 )
    dpd.show()
}

 

728x90