JakeWharton / ThreeTenABP

An adaptation of the JSR-310 backport for Android.
Apache License 2.0
3.55k stars 133 forks source link

How to handle language/locale changes after init()? #96

Closed prefect4742 closed 5 years ago

prefect4742 commented 5 years ago

Is there a way to handle the case where my app is already running, but user changes the language/locale of the system? I tried calling init() in onConfigurationChanged() but nothing happens - since init() is set to only execute anything on first call.

JakeWharton commented 5 years ago

I'm not sure what this library would need to do. Can you clarify what isn't working after the locale change?

prefect4742 commented 5 years ago

Different locales have different formatting of dates and times. If I start my app with US English it might be 02/16/2019 3:45pm but with Swedish it will be 2019-02-16 15:45.

But if I start the app, then switch to settings and change the language, and then resume the app, the library still returns strings of the first locale/language. Unless I missed something when I tested it.

JakeWharton commented 5 years ago

A locale change will cause all activities in your app to restart where they should pick up the new format.

What API are you calling to perform formatting?

prefect4742 commented 5 years ago

The view that's being shown is using databinding and calls the static method above to convert a ZoneDateTime to a string.

object Converter {
    private lateinit var formatter: DateTimeFormatter

    fun init() {
        formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
    }

    object Dates {
        @JvmStatic
        fun toString(dateTime: ZonedDateTime): String = dateTime.format(formatter)
    }
}

I can see that this gets called when I change the device language and then switch back to my app. But even if the formatter is set when the language has changed, it returns a string in the same format as when my app started. Which is why I thought that the library only reads the locale when AndroidThreeTen.init(ApplicationContext) is called.

prefect4742 commented 5 years ago

Well this is embarassing... it does indeed work, I just wasn't paying close enough attention.

The medium date format for US is "Feb 16, 2019 10:01:23" The medium date format for Sweden is "16 Feb 2019 10:01:23"

On top of that I also had "use 24 hour format" turned on and not "automatic 24 hour format" so I never got the am/pm times for the US locale. Worth noting though is that the manual Android setting "use 24-hour format" doesn't seem to cause a configuration change, at least not on Oreo.

JakeWharton commented 5 years ago

Glad it's working. Thanks for following up.