iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0
Software Development

Kotlin 30 天,通過每天一個小 demo 學習 Android 開發系列 第 11

Kotlin 開發第 11 天 Alarm ( DatePickerDialog + AlertDialog)

ActivitySchedule
一個活動日期確認的應用。

  • 提供日期、時間的選擇
  • 提供一個按鈕,點下後顯示確認日期提示

涉及到的元素

  • Calendar
  • DatePickerDialog / TimePickerDialog
  • SimpleDateFormat
  • AlertDialog

TimePickerDialog

我們通過一個 cal 變量來記錄使用者設定的時間,一開始會先取得當前時間。

var cal = Calendar.getInstance()

當使用者點下輸入框的時候就跳出 TimePickerDialog,其中的時間取自我們的 cal 。

    private var timeTextEditHandler = View.OnClickListener { view ->

        TimePickerDialog(this, timeSetListener,
                cal.get(Calendar.HOUR),
                cal.get(Calendar.MINUTE),
                true
        ).show()
    }

當使用者選好時間以後,會執行我們提供的 timeSetListener:

先改變我們的 cal 的時間(其中 .HOUR_OF_DAY 是 24小時制,而 .HOUR 是 12小時制度)。

然後改變 timeEditText 顯示的時間。

    val timeSetListener = TimePickerDialog.OnTimeSetListener{ view, hour, minute ->

        cal.set(Calendar.HOUR, hour)
        cal.set(Calendar.MINUTE, minute)

        val time = SimpleDateFormat("HH:mm", Locale.TAIWAN)
        timeEditText.text = time.format(cal.time)
    }

SimpleDateFormat

可以通過類似 iOS 的 DateFormatter 的 SimpleDateFormat 來指定時間格式。

        val time = SimpleDateFormat("HH:mm", Locale.TAIWAN)
        timeEditText.text = time.format(cal.time)

AlertDialog

https://ithelp.ithome.com.tw/upload/images/20171214/20107329tmVoWhR6TO.png
通過 AlertDialog.Builder() 來建立 Dialog 的畫面。

        val time = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.TAIWAN).format(cal.time)

        // setup dialog builder
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Party time confirm")
        builder.setMessage("$time")
        builder.setPositiveButton("Confirm",{ dialog, whichButton ->
            println("confirm")
        })

        builder.setNegativeButton("Cancel", { dialog, whichButton ->
            println("cancel")
        })

        // create dialog and show it
        val dialog = builder.create()
        dialog.show()

參考


上一篇
Kotlin 開發第 10 天 ProgressControl ( ProgressBar + Handler )
下一篇
Kotlin 開發第 12 天 GithubStars ( OkHttp + RecyclerView)
系列文
Kotlin 30 天,通過每天一個小 demo 學習 Android 開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言