DatePickerDialog 是我們常用系統自帶的日期選擇對話框,但有時我們僅需要選擇 年月 或者僅需要選擇 月日,這種情況我們應該如何快速實現該功能呢?
直接百度搜索給出的帖子裏最接近正確答案的是這篇文章:
【Android DatePickerDialog只顯示年月或只顯示月日】你直接照搬,但是你如果直接照搬,大概率是沒有效果,原因在於Dialog的格式!
這些文章大部分都寫的很早,在19年的今天已經失去了時效性,而新的文章大多也是抄來抄去,不做分辨的就照搬過來。
參考文章:【DatePickerDialog的樣式改變】,你就能的得知,實例化 DatePickerDialog 時使用不同的 style 會使用不同的佈局顯示,要想實現 年月 的選擇,需要使用 DatePickerDialog.THEME_HOLO_LIGHT 這一 style。
完整代碼如下:
//僅選擇年月
private fun showMonthPicker() {
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
//一定要設置 DatePickerDialog 的 style
val datePickerDialog= DatePickerDialog(this, DatePickerDialog.THEME_HOLO_LIGHT,DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
calendar.set(year, month, dayOfMonth,0,0)
val time = calendar.timeInMillis/1000
val day = time.dateSecondToString("yyyy-MM-dd")!!
Logger.d("所選日期的時間爲: ${time.dateSecondToString()}")
}, year, month, day)
val datePicker = datePickerDialog.datePicker
datePicker.maxDate= Date().time //限制最大時間
datePickerDialog.show()
((datePicker?.getChildAt(0)as ViewGroup?)?.getChildAt(0)as ViewGroup?)?.getChildAt(2)?.visibility = View.GONE
}