Skip to content

Instantly share code, notes, and snippets.

@JoachimR
Created November 20, 2017 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoachimR/f82b2b371b1ced4a09918c970e045d4f to your computer and use it in GitHub Desktop.
Save JoachimR/f82b2b371b1ced4a09918c970e045d4f to your computer and use it in GitHub Desktop.
ChooseDayDialog with optional request code
import android.app.DatePickerDialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import java.util.*
class ChooseDayDialog : DialogFragment() {
companion object {
private val KEY_INITIAL_TIMESTAMP = "KEY_INITIAL_TIMESTAMP"
private val KEY_REQUEST_CODE = "KEY_REQUEST_CODE"
private val DEFAULT_REQUEST_CODE = 20
fun createInstance(initialTimestamp: Long,
requestCode: Int = DEFAULT_REQUEST_CODE) =
ChooseDayDialog().apply {
arguments = Bundle().apply {
putLong(KEY_INITIAL_TIMESTAMP, initialTimestamp)
putInt(KEY_REQUEST_CODE, requestCode)
}
}
}
interface OnDayChosenListener {
fun onDayChosen(requestCode: Int, year: Int, month: Int, dayOfMonth: Int)
}
private lateinit var listener: OnDayChosenListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activity = activity
if (activity is OnDayChosenListener) {
listener = activity
} else {
throw IllegalStateException("Activity must implement OnDayChosenListener")
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val timestamp = arguments?.getLong(KEY_INITIAL_TIMESTAMP, -1L) ?: -1L
if (timestamp == -1L) {
throw IllegalStateException("no initial time given")
}
val requestCode = arguments?.getInt(KEY_REQUEST_CODE, DEFAULT_REQUEST_CODE)
?: DEFAULT_REQUEST_CODE
val calendar = Calendar.getInstance().apply {
timeInMillis = timestamp
}
return DatePickerDialog(activity,
DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
listener.onDayChosen(requestCode, year, month, dayOfMonth)
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment