Created
November 20, 2017 15:39
-
-
Save JoachimR/f82b2b371b1ced4a09918c970e045d4f to your computer and use it in GitHub Desktop.
ChooseDayDialog with optional request code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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