Android: How to get string in specific locale WITHOUT changing the current locale

前端 未结 5 2010

Use Case: Logging error messages as displayed to the user.

However you don\'t want to have messages in your log that depend on the locale of the user\'s device. On t

5条回答
  •  不知归路
    2020-12-05 07:08

    Thanks to @Khaled Lela answer, I've made a Kotlin extension:

    fun Context.getStringByLocale(@StringRes stringRes: Int, locale: Locale, vararg formatArgs: Any): String {
        val configuration = Configuration(resources.configuration)
        configuration.setLocale(locale)
        return createConfigurationContext(configuration).resources.getString(stringRes, *formatArgs)
    }
    

    And I'm using directly within an Activity, Fragment or Context related classes, just simply calling:

    getStringByLocale(R.string.my_text, Locale.UK) or with arguments:

    getStringByLocale(R.string.my_other_text, Locale.RU, arg1, arg2, arg3)

提交回复
热议问题