How to change language in kotlin (locale) - android

I have 2 string files "en" and "tr". When I change my telephone's language string files change automatically(I didn't write extra code for this result and I don't know how this happen). I want change string files with programmatically.
I used this code. I get Toast message but language doesn't change.WHY? I used these code before for another application which I write with java not Kotlin and these code work fine. Please don't say duplicate because I read a lot of questions. I try a lot of things until now 4 hours.
override fun onResume() {
buttonDate()
changeLanguage()
super.onResume()
}
fun changeLanguage(){
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val language = sharedPreferences.getString("language","bak")
Toast.makeText(applicationContext,language,Toast.LENGTH_SHORT).show()
if(language=="English"){
Toast.makeText(applicationContext,"English",Toast.LENGTH_SHORT).show()
language("")
}else if(language=="Turkish"){
Toast.makeText(applicationContext,"Turkish",Toast.LENGTH_SHORT).show()
language("tr")
}
}
fun language(language: String){
val locale = Locale(language)
Locale.setDefault(locale)
val resources = getResources()
val configuration = resources.getConfiguration()
configuration.locale = locale
resources.updateConfiguration(configuration, resources.getDisplayMetrics())
}

You need to update configuration even before onCreate is called. To do that
create a BaseActivity class like this
open class BaseActivity : AppCompatActivity() {
companion object {
public var dLocale: Locale? = null
}
init {
updateConfig(this)
}
fun updateConfig(wrapper: ContextThemeWrapper) {
if(dLocale==Locale("") ) // Do nothing if dLocale is null
return
Locale.setDefault(dLocale)
val configuration = Configuration()
configuration.setLocale(dLocale)
wrapper.applyOverrideConfiguration(configuration)
}
}
Extend you activities from this class.
Set dLocale in you App class like this:
class App : Application() {
override fun onCreate() {
super.onCreate()
var change = ""
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
val language = sharedPreferences.getString("language", "bak")
if (language == "Turkish") {
change="tr"
} else if (language=="English" ) {
change = "en"
}else {
change =""
}
BaseActivity.dLocale = Locale(change) //set any locale you want here
}
}
You will also need to set App class in your manifest file like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
//..
<application
android:name=".App"
//..>
</application>
</manifest>
Note: We should set dLocale only in App onCreate to ensure that all activities have same language.

Related

Changing the App Language not working correctly (Kotlin)

I have a Splash screen in my kotlin app, where I do some stuff like loading data. Currently it is only in german and I wanted to add english as additional language.
I've create the strings resources and so on.
Now I have added a bit of code to the Splash-Screen, where it checks, if the user already set a preferenced language (saved in sharedPreferences).
When there is nothing saved, a simple alertdialog pops up asking the user for his preference and sets everything accordingly.
Then the splashscreen is reloaded. When I choose english on my device (system language is german), the splash screen gets the correct string resources (english).
But when it changes to the MainActivity, it is german again. Only after restarting the app, everything is in english.
Here is how I change the language on my splashscreen:
private lateinit var mainIntent : Intent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
var localeToSet: String? = prefs.getString("language", "")
if(localeToSet == null || localeToSet.equals("")){
val languages = arrayOf("Deutsch", "English")
val langSelectorBuilder = AlertDialog.Builder(this)
langSelectorBuilder.setTitle(R.string.selectLanguageText)
langSelectorBuilder.setCancelable(false)
langSelectorBuilder.setSingleChoiceItems(languages, -1) { dialog, selection ->
when(selection) {
0 -> {
localeToSet = "de"
setLocale("de")
}
1 -> {
localeToSet = "en"
setLocale("en")
}
}
recreate()
dialog.dismiss()
}.setOnDismissListener {
Handler().postDelayed({
startActivity(mainIntent)
finish()
}, SPLASH_TIME_OUT)
}
langSelectorBuilder.create().show()
}
else{
setLocale(localeToSet!!)
Handler().postDelayed({
startActivity(mainIntent)
finish()
}, SPLASH_TIME_OUT)
}
setContentView(R.layout.activity_splash_screen)
}
private fun createIntent(localeToSet: String){
mainIntent = Intent(this#SplashScreenActivity, MainActivity::class.java).apply {
//Do stuff and pass data to mainactivity
}
private fun setLocale(localeToSet: String) {
createIntent(localeToSet)
val config = resources.configuration
val locale = Locale(localeToSet)
Locale.setDefault(locale)
config.locale = locale
resources.updateConfiguration(config, resources.displayMetrics)
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
val editor: SharedPreferences.Editor = prefs.edit()
editor.putString("language", localeToSet)
editor.apply()
}
Nevermind, found the issue:
val langSelectorBuilder = AlertDialog.Builder(this)
langSelectorBuilder.setTitle(R.string.selectLanguageText)
langSelectorBuilder.setCancelable(false)
langSelectorBuilder.setSingleChoiceItems(languages, -1) { dialog, selection ->
when(selection) {
0 -> {
localeToSet = "de"
setLocale("de")
}
1 -> {
localeToSet = "en"
setLocale("en")
}
}
recreate()
dialog.dismiss()
}.setOnDismissListener {
finish()
}
langSelectorBuilder.create().show()
Without starting the MainActivity here, it works like it should

setting language before setContentView results in unending loop

I have a fragment with settings of an app that saves the user selected mode and language
( a bit of code:
binding.languageButton.setOnClickListener{
builder = AlertDialog.Builder(requireContext())
builder.setTitle(getString(R.string.setLanguage))
builder.setItems(langArray) { _, which ->
val sharedPref = requireActivity().getSharedPreferences("Settings", Context.MODE_PRIVATE).edit()
sharedPref.putString("LANGUAGE", langArray[which]).apply()
checkUserPreferences()
changeLanguage(langArray[which])
binding.languageButton.text = langArray[which]
}
builder.create()
builder.show()
}
}
private fun changeLanguage(language: String) {
if(language != binding.languageButton.text.toString()){
val local = Locale(language)
val dm = resources.displayMetrics
val con = resources.configuration
con.locale = local
resources.updateConfiguration(con, dm)
val refresh = Intent(
requireContext(),
MainActivity::class.java
)
refresh.putExtra(binding.languageButton.text.toString(), language)
startActivity(refresh)
}
}
and that part (as mentioned) saves mode and selected language to sharedPreferences that I later want to use in mainActivity and other fragments, and I've put in MainActivity:
private fun loadPreferences(){
val preferences = getSharedPreferences("Settings", Activity.MODE_PRIVATE)
Log.i(TAG, preferences.getString("LANGUAGE", "eng").toString())
Log.i(TAG, preferences.getInt("MODE", 1).toString())
val local = Locale(preferences.getString("LANGUAGE", "eng").toString())
val dm = resources.displayMetrics
val con = resources.configuration
con.locale = local
resources.updateConfiguration(con, dm)
val refresh = Intent(
this.baseContext,
MainActivity::class.java
)
refresh.putExtra(preferences.getString("LANGUAGE", "eng").toString(),
preferences.getString("LANGUAGE", "eng"))
startActivity(refresh)
}
and this is referenced in:
class MainActivity : AppCompatActivity() {
// TODO: IT'S THE ONE
companion object {
private const val TAG = "MainActivity"
private const val CHANNEL_ID = "plantz_app_channel_01"
private const val notificationId = 909
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loadPreferences()
setContentView(R.layout.activity_main)
// ...
and after running the app It only shows the app logo and logs sharedPreferences but the app doesn't go any further, I've tried to tweak with it for a bit but It hasn't done much, any ideas what should I change to make it work?
Thanks in advance :)
This infinity loop happens because when the MainActivity is going to be opened you call loadPreferences() in onCreate method where you open a new instance of MainActivity from there.
So the infinity loop goes like below:
onCreate() method of MainActivity is called
loadPreferences() method is called
in loadPreferences() after you have set the language from SharedPreferences you start a new instance of your MainActivity which redirects you back to step 1.
To avoid this infinity loop remove the below lines from your loadPreferences() method:
val refresh = Intent(this.baseContext,MainActivity::class.java)
refresh.putExtra(preferences.getString("LANGUAGE", "eng").toString(), preferences.getString("LANGUAGE", "eng"))
startActivity(refresh)

Localization sometimes reset to system locale

I have a single activity application, language setting mostly works as intended. I set every view's texts in onCreateView() by the resource id of the text. But sometimes, when I enter my application, the language is the system default instead of the selected language. The same happens when I navigate to the app from deep link (widget or notification).And when I navigate to another fragment and return, everything becomes right with right locale.
I tried to debug my application to discover the reason. Every text by resource id I got according to system default, not the language selected. When I instead wrap my fragment context and then fetch the text, I get the corect result.
This is how I set my language:
private fun changeLang(lang: String, country: String) {
activity?.let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResources(it, lang, country)
}
updateResourcesLegacy(it, lang, country)
}
}
#TargetApi(Build.VERSION_CODES.N)
private fun updateResources(context: Context, language: String, country: String) {
val locale = Locale(language, country)
Locale.setDefault(locale)
val resources: Resources = context.resources
val configuration: Configuration = resources.configuration
configuration.setLocale(locale)
context.createConfigurationContext(configuration)
}
private fun updateResourcesLegacy(context: Context, language: String, country: String) {
val locale = Locale(language, country)
Locale.setDefault(locale)
val resources: Resources = context.resources
val configuration: Configuration = resources.configuration
configuration.locale = locale
resources.updateConfiguration(configuration, resources.displayMetrics)
}
In my activity I overrode the following method:
override fun attachBaseContext(newBase: Context?) {
newBase?.let {
val pref = Preference(PreferenceHelper.customPrefs(it))
super.attachBaseContext(ContextWrapper.wrap(newBase, pref.language, pref.country))
}
}
class ContextWrapper(base: Context?) : android.content.ContextWrapper(base) {
companion object {
fun wrap(context: Context?, lang: String? = "uz", country: String? = ""): ContextWrapper =
wrap(context, Locale(lang, country))
fun wrap(context: Context?, newLocale: Locale): ContextWrapper {
var localizedContext = context
val res = localizedContext?.resources
val configuration = res?.configuration
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
configuration?.setLocale(newLocale)
val localeList = LocaleList(newLocale)
LocaleList.setDefault(localeList)
configuration?.setLocales(localeList)
localizedContext = localizedContext?.createConfigurationContext(configuration!!)
}
else -> {
configuration?.setLocale(newLocale)
localizedContext = localizedContext?.createConfigurationContext(configuration!!)
}
}
res?.updateConfiguration(configuration, res.displayMetrics)
return ContextWrapper(localizedContext)
}
}
}
Try to write both at the same time:
configuration.setLocale(locale)
configuration.locale = locale
try this in ContextWrapper class and updateResources function
The reason was not setting the language for application context. Application resources did not get updated. I applied the locale on attachBaseContext method of my application class.

Change locale programmatically in Kotlin

I had some codes for change locale programmatically in Java. But when my application migrated to Kotlin, I can't change locale any more.
For example this code in Java worked very good :
public static final void setAppLocale(String language, Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Resources resources = activity.getResources();
Configuration configuration = resources.getConfiguration();
configuration.setLocale(new Locale(language));
activity.getApplicationContext().createConfigurationContext(configuration);
} else {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = activity.getResources().getConfiguration();
config.locale = locale;
activity.getResources().updateConfiguration(config,
activity.getResources().getDisplayMetrics());
}
}
I tried many codes in Kotlin but non of them worked for me. This is my last try:
fun changeLanguage(context: Context, language : String) {
val locale = Locale(language)
Locale.setDefault(locale)
val config = context.resources.configuration
config.setLocale(locale)
context.createConfigurationContext(config)
context.resources.updateConfiguration(config, context.resources.displayMetrics)
}
How can I change application's local in Kotlin? Old codes that were written in Java did not work in Kotlin application.
Create a Context helper class let's say
class ApplicationLanguageHelper(base: Context) : ContextThemeWrapper(base, R.style.AppTheme) {
companion object {
fun wrap(context: Context, language: String): ContextThemeWrapper {
var context = context
val config = context.resources.configuration
if (language != "") {
val locale = Locale(language)
Locale.setDefault(locale)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setSystemLocale(config, locale)
} else {
setSystemLocaleLegacy(config, locale)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLayoutDirection(locale)
context = context.createConfigurationContext(config)
} else {
context.resources.updateConfiguration(config, context.resources.displayMetrics)
}
}
return ApplicationLanguageHelper(context)
}
#SuppressWarnings("deprecation")
fun setSystemLocaleLegacy(config: Configuration, locale: Locale) {
config.locale = locale
}
#TargetApi(Build.VERSION_CODES.N)
fun setSystemLocale(config: Configuration, locale: Locale) {
config.setLocale(locale)
}
}
}
And in your Activity you can override attachBaseContext
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(ApplicationLanguageHelper.wrap(newBase!!, "fa"))
}
To Change the language you can use a Spinner or any other preferred way, to call the following method OnClick
private fun changeApplicationLanguage(language:String){
val sharedPreferencesEditor = sharedPreferences.edit()
when (language) {
ENGLISH -> sharedPreferencesEditor?.putString(SELECTED_LANGUAGE, ENGLISH)
PERSIAN -> sharedPreferencesEditor?.putString(SELECTED_LANGUAGE, PERSIAN)
PASHTO -> sharedPreferencesEditor?.putString(SELECTED_LANGUAGE, PASHTO)
}
sharedPreferencesEditor.putBoolean(LANGUAGE_IS_SELECTED, true)
sharedPreferencesEditor?.apply()
recreate()
}
make sure you define sharedPreferences and also SELECTED_LANGUAGE , ENGLISH etc, consts
const val SELECTED_LANGUAGE = "language"
const val ENGLISH = "en"
const val PERSIAN = "fa"
const val PASHTO = "ps"
private lateinit var sharedPreferences: SharedPreferences
and also initialize sharedPreferences in onCreate method after setContent
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this#Your_Activity_Name)
also Override the base context by adding the following code
// Overwrite the context
override fun attachBaseContext(newBase: Context?) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(newBase)
val lang = sharedPreferences.getString(SELECTED_LANGUAGE, "en")
super.attachBaseContext(ApplicationLanguageHelper.wrap(newBase!!, lang!!))
}
I am sure this method is not an optimal solution, but, this might help
Try this
fun setAppLocale(languageFromPreference: String?, context: Context)
{
if (languageFromPreference != null) {
val resources: Resources = context.resources
val dm: DisplayMetrics = resources.displayMetrics
val config: Configuration = resources.configuration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLocale(Locale(languageFromPreference.toLowerCase(Locale.ROOT)))
} else {
config.setLocale(Locale(languageFromPreference.toLowerCase(Locale.ROOT)))
}
resources.updateConfiguration(config, dm)
}
}
You can set the App Locale within activities by accessing this function from the activities
..
super.onCreate(savedInstanceState)
setAppLocale(pref.getLanguageFromPreference().toString(), this)
setContentView(R.layout.activity_main)
...
pref.getLanguageFromPreference() returns the langugae string (For example : "en")

Change language programmatically (Android N 7.0 - API 24)

I'm using the following code to set specific language in my app. Language is saved into SharedPreferences within the app. And it works perfectly up to API level 23. With Android N SharedPreferences works well too, it returns the correct language code-string, but it does not change the locale (sets default language of the phone). What could be wrong?
Update 1: When I use Log.v("MyLog", config.locale.toString()); immediately after res.updateConfiguration(config, dm) it returns correct locale, but language of the app does not changed.
Update 2: I also mentioned that if I change locale and then restart the activity (using new intent and finish on the old one), it changes the language properly, it even shows correct language after rotation. But when I close the app and open it again, I get default language. It's weird.
public class ActivityMain extends AppCompatActivity {
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set locale
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
String lang = pref.getString(ActivityMain.LANGUAGE_SAVED, "no_language");
if (!lang.equals("no_language")) {
Resources res = context.getResources();
Locale locale = new Locale(lang);
Locale.setDefault(locale);
DisplayMetrics dm = res.getDisplayMetrics();
Configuration config = res.getConfiguration();
if (Build.VERSION.SDK_INT >= 17) {
config.setLocale(locale);
} else {
config.locale = locale;
}
}
res.updateConfiguration(config, dm);
setContentView(R.layout.activity_main);
//...
}
//...
}
Update 3: THE ANSWER IS ALSO HERE: https://stackoverflow.com/a/40849142/3935063
Create a new class extends ContextWrapper
public class MyContextWrapper extends ContextWrapper {
public MyContextWrapper(Context base) {
super(base);
}
#TargetApi(Build.VERSION_CODES.N)
public static ContextWrapper wrap(Context context, Locale newLocale) {
Resources res = context.getResources();
Configuration configuration = res.getConfiguration();
if (VersionUtils.isAfter24()) {
configuration.setLocale(newLocale);
LocaleList localeList = new LocaleList(newLocale);
LocaleList.setDefault(localeList);
configuration.setLocales(localeList);
context = context.createConfigurationContext(configuration);
} else if (VersionUtils.isAfter17()) {
configuration.setLocale(newLocale);
context = context.createConfigurationContext(configuration);
} else {
configuration.locale = newLocale;
res.updateConfiguration(configuration, res.getDisplayMetrics());
}
return new ContextWrapper(context);
}
}
override Activity's attachBaseContext method
#Override
protected void attachBaseContext(Context newBase) {
Locale languageType = LanguageUtil.getLanguageType(mContext);
super.attachBaseContext(MyContextWrapper.wrap(newBase, languageType));
}
finish the activity and start it again,new locale will become effective.
demo:https://github.com/fanturbo/MultiLanguageDemo
I faced this issue when i started to target SDK 29. The LocaleHelper that i created worked on every version from my min SDK(21) to 29 but specifically on Android N it didn't use to work. So after searching many stack overflow answers and visiting https://issuetracker.google.com/issues/37123942 , i managed to find/modify a solution which is now working on all android versions.
So, first i took help of https://gunhansancar.com/change-language-programmatically-in-android/ to get a locale helper. Then i modified it to my needs like this:
object LocaleHelper {
const val TAG = "LocaleHelper"
fun updateLocale(base: Context): Context {
Log.e(TAG, "updateLocale: called");
val preferenceHelper = PreferenceHelper(base)
preferenceHelper.getStringPreference(PreferenceHelper.KEY_LANGUAGE).let {
return if (it.isNotEmpty()) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
updateResources(base, it)
} else {
updateResourcesLegacy(base, it)
}
} else {
base
}
}
}
private fun updateResources(base: Context, language: String): Context{
val loc = Locale(language)
Locale.setDefault(loc)
val configuration = base.resources.configuration
configuration.setLocale(loc)
return base.createConfigurationContext(configuration)
}
#Suppress("DEPRECATION")
private fun updateResourcesLegacy(base: Context, language: String): Context{
val locale = Locale(language)
Locale.setDefault(locale)
val configuration = base.resources.configuration
configuration.locale = locale
configuration.setLayoutDirection(locale)
base.resources.updateConfiguration(configuration, base.resources.displayMetrics)
// Log.e(TAG, "updateLocale: returning for below N")
return base
}
}
Then, in the base activity, override the attachBaseContext method like:
/**
* While attaching the base context, make sure to attach it using locale helper.
* This helps in getting localized resources in every activity
*/
override fun attachBaseContext(newBase: Context?) {
var context = newBase
newBase?.let {
context = LocaleHelper.updateLocale(it)
}
super.attachBaseContext(context)
}
But i found that this used to work on Nougat and above and not in marshmallow and lollipop. So, I tried this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Update the locale here before loading the layout to get localized strings.
LocaleHelper.updateLocale(this)
In the oncreate of base activity i called this method. And it started working. But there were instances where if we kill the app from recent tasks and then start it, the first screen wasn't localized. So to tackle that, i created a static temp variable in app class that held the value for initial app instance.
companion object {
val TAG = "App"
var isFirstLoad = true
}
And in my first screen of app, i did this in oncreate:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Need to call this so that when the application is opened for first time and we need to update the locale.
if(App.isFirstLoad) {
LocaleHelper.updateLocale(this)
App.isFirstLoad = false
}
setContentView(R.layout.activity_dash_board)
Now i tested on redmi 4a (Android 7) on which it wasn't working previously, emulators of sdk 21,23,27,29 and in redmi note 5 pro and pixel devices. In all these, the in app language selection works properly.
Sorry for the long post, but please do suggest for an optimized way!
Thanks!
EDIT 1:
So i faced this issue where it was not working on android 7.1 (sdk 25). I asked gunhan for help and then made this change.
override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
super.applyOverrideConfiguration(LocaleHelper.applyOverrideConfiguration(baseContext, overrideConfiguration))
}
I added this function in my LocaleHelper:
fun applyOverrideConfiguration(base: Context, overrideConfiguration: Configuration?): Configuration? {
if (overrideConfiguration != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
val uiMode = overrideConfiguration.uiMode
overrideConfiguration.setTo(base.resources.configuration)
overrideConfiguration.uiMode = uiMode
}
return overrideConfiguration
}
And now it's finally working.
Thanks Gunhan!
I had the same problem but with Android 5, 6 and 7. After a lot of searches, the solution is in this post : Change Locale not work after migrate to Androidx (see the comment of Ehsan Shadi and not the "solution").
First, you have to update your library appcompat to 1.2.0 (fix for locale, see here : https://developer.android.com/jetpack/androidx/releases/appcompat#1.2.0) and you have to override the applyOverrideConfiguration function in your base activity.
I have tested this solution on all API (19 to 30 - Android 4.4 to 11) and it's worked perfectly :)
This approach will work on all api level device, Make sure to recreate activity on changing language programatically.
1.Use Base Activity for attachBaseContext to set the locale language And extend this activity for all activities
open class BaseAppCompactActivity() : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LocaleHelper.onAttach(newBase))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}
2.Use Application attachBaseContext and onConfigurationChanged to set the locale language
public class MyApplication extends Application {
private static MyApplication application;
#Override
public void onCreate() {
super.onCreate();
}
public static MyApplication getApplication () {
return application;
}
/**
* overide to change local sothat language can be chnaged from android device nogaut and above
*/
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.INSTANCE.onAttach(base));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
/**
* also handle change language if device language changed
*/
super.onConfigurationChanged(newConfig);
}
}
3.Use Locale Helper for handling language changes , this approch work on all device
object LocaleHelper {
fun onAttach(context: Context, defaultLanguage: String): Context {
return setLocale(context, defaultLanguage)
}
fun setLocale(context: Context, language: String): Context {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResources(context, language)
} else updateResourcesLegacy(context, language)
}
#TargetApi(Build.VERSION_CODES.N)
private fun updateResources(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val configuration = context.getResources().getConfiguration()
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
return context.createConfigurationContext(configuration)
}
private fun updateResourcesLegacy(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.getResources()
val configuration = resources.getConfiguration()
configuration.locale = locale
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale)
}
resources.updateConfiguration(configuration, resources.getDisplayMetrics())
return context
}
}

Categories

Resources