Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android Localize months in DatePickerDialog or am/pm in TimePickerDialog
import timber.log.Timber
/**
* Patch date picker or time picker to use custom months or am/pm
* From: https://stackoverflow.com/a/33599403/2897341
*
* @param picker [android.widget.DatePicker] or [android.widget.TimePicker]
* @param values months or am/pm
*/
fun localizePicker(picker: Any, values: Array<String>) {
var target = picker
try {
var fields = target.javaClass.declaredFields
for (field in fields) {
// If there's a delegate, we use it instead.
if (field.name == "mDelegate") {
field.isAccessible = true
target = field.get(target)
fields = target.javaClass.declaredFields
break
}
}
for (field in fields) {
if (field.name == "mAmPmStrings" || field.name == "mShortMonths") {
field.isAccessible = true
field.set(target, values)
} else if (field.name == "mAmPmSpinner" || field.name == "mMonthSpinner") {
field.isAccessible = true
val innerObject = field.get(target)
val method = innerObject.javaClass.getDeclaredMethod(
"setDisplayedValues", Array<String>::class.java
)
method.isAccessible = true
method.invoke(innerObject, values as Any)
}
}
val methods = target.javaClass.declaredMethods
for (method in methods) {
if (method.name.equals("updateAmPmControl") || method.name.equals("updateSpinners")) {
method.isAccessible = true
method.invoke(target)
break
}
}
} catch (e: Exception) {
Timber.e(e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment