DatePickerDialog 仅显示年月

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
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章