Android Application

Kotlin 고급 위젯 - 날짜와 시간 관련 위젯 : 타임피커(TimePicker)와 데이트피커(DatePicker) Dial…

작성자 임베디드코리아 작성일23-09-24 00:56 조회1,559회 댓글0건

첨부파일

------------------------------------------------------------------------------------
      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">

    <Button
        android:id="@+id/btn_load_calendar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="날짜 선택"/>

    <TextView
        android:id="@+id/text_selected_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_weight="1"/>

    <Button
        android:id="@+id/btn_load_timer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="시간 선택"/>

    <TextView
        android:id="@+id/text_selected_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_weight="1"/>

</LinearLayout>

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

        var BTN_load_calendar: Button = findViewById(R.id.btn_load_calendar)
        var BTN_load_timer: Button = findViewById(R.id.btn_load_timer)
        var TEXT_selected_date: TextView = findViewById(R.id.text_selected_date)
        var TEXT_selected_time: TextView = findViewById(R.id.text_selected_time)

        val cal = Calendar.getInstance()

        // 달력 로드
        BTN_load_calendar.setOnClickListener {
            DatePickerDialog(this, DatePickerDialog.OnDateSetListener { datePicker, y, m, d ->
                TEXT_selected_date.text = "$y/${m+1}/$d"
            }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show()
        }

        // 타이머 로드
        BTN_load_timer.setOnClickListener {
            TimePickerDialog(this, TimePickerDialog.OnTimeSetListener { timePicker, h, m ->
                TEXT_selected_time.text = "$h:$m"
            }, cal.get(Calendar.HOUR), cal.get(Calendar.MINUTE), true ).show()
        }

    }
}