Set Locale programmatically

后端 未结 14 1453
Happy的楠姐
Happy的楠姐 2020-11-22 05:55

My app supports 3 (soon 4) languages. Since several locales are quite similar I\'d like to give the user the option to change locale in my application, for instance an Itali

14条回答
  •  悲哀的现实
    2020-11-22 06:19

    There is a super simple way.

    in BaseActivity, Activity or Fragment override attachBaseContext

     override fun attachBaseContext(context: Context) {
        super.attachBaseContext(context.changeLocale("tr"))
    }
    

    extension

    fun Context.changeLocale(language:String): Context {
        val locale = Locale(language)
        Locale.setDefault(locale)
        val config = this.resources.configuration
        config.setLocale(locale)
        return createConfigurationContext(config)
    }
    

提交回复
热议问题