How to change language locale at Android without restart activity

Sometimes you may need to change Android language from your activity and you don't want to restart Android activity. Restarting give user a little glitch effect which is not good user experience. 

Few people restart activity or use recreate() function to update the language user interface. 

You can follow below instruction to prevent restart or recreate your activity. 

Step 1: First you need to change the locale using following code.

Locale locale = new Locale(localeCode.toLowerCase());
Resources resources = getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
Configuration configuration = resources.getConfiguration();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR1){
configuration.setLocale(locale);
} else {
configuration.locale = locale;
}
resources.updateConfiguration(configuration, displayMetrics);
onConfigurationChanged(configuration);

Step 2: update your current interface from below override method:

@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
user_name.setHint(getString(R.string.username)); // update your all current screen UI
super.onConfigurationChanged(newConfig);
}

Step 3: Update your activity manifest file with below code


<activity
android:name=".activity.LanguageChangeActivity"
android:launchMode="singleInstance"
android:configChanges="locale|layoutDirection"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />

Now you can able to change language settings without restart or recreate() activity. 


Happy coding and bug fixing!!!


Post a Comment

0 Comments