Кратко о DatePickerDialog

Создам простейшую Activity и класс, наследующий DialogFragment():

class DatePickerFragment: DialogFragment() {

    private lateinit var callback: Callback
    private lateinit var calendar: Calendar

    override fun onCreateDialog(savedInstanceState: Bundle?) = DatePickerDialog(
        activity!!,
        DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth -> callback.onDateSelected(calendar.apply { set(year, month, dayOfMonth) }) },
        calendar.get(Calendar.YEAR),
        calendar.get(Calendar.MONTH),
        calendar.get(Calendar.DAY_OF_MONTH)
    )

    fun display(manager: FragmentManager, tag: String, calendar: Calendar = Calendar.getInstance(), callback: Callback) {
        this.calendar = calendar
        this.callback = callback
        super.show(manager, tag)
    }

    interface Callback {
        fun onDateSelected(calendar: Calendar)
    }
}
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        DatePickerFragment().display(
            manager = supportFragmentManager,
            tag = DIALOG_TAG,
            calendar = Calendar.getInstance().apply { set(1976, 0, 5) },
            callback = object : DatePickerFragment.Callback {
                override fun onDateSelected(calendar: Calendar) {
                    Toast.makeText(this@MainActivity, SimpleDateFormat(DATE_FORMAT_PATTERN, Locale.US).format(calendar.time), Toast.LENGTH_SHORT).show()
                }
            })
    }

    companion object {
        private const val DIALOG_TAG = "DatePicker"
        private const val DATE_FORMAT_PATTERN = "EEE, MMM d, YYYY"
    }
}

Собственно, это всё 🙂

Код на GitLab.

Добавить комментарий

Закрыть меню