Reputation: 733
I have a problem with changing all text in one activity of my application... i am using this code to change language:
else if (LANGUAGE.equals("Russian"))
{
Resources res = this.getResources();
// Change locale settings in the app.
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale("ru-rRU");
res.updateConfiguration(conf, dm);
}
in AndroidManifest i have added this string:
<activity
android:name="com.vladimir.expert_suise.ThirdScreen"
android:label="@string/title_activity_third_screen"
android:configChanges="locale">
</activity>
and when i launch my app on my phone, language is not changed =( here is screenshoot -
so what is wrong with my code?(
P.S i have also created values-ru-rRU folder and inserted there translated string.xml file
Upvotes: 2
Views: 3238
Reputation: 2815
To set language of one activity only irrespective of Application language (locale), below code can be used
public override fun attachBaseContext(context: Context) {
// pass desired language
super.attachBaseContext(LocaleHelper.onAttach(context, "hi"));
}
LocaleHelper.java
public class LocaleHelper {
public static Context onAttach(Context context, String defaultLanguage) {
return setLocale(context, defaultLanguage);
}
public static Context setLocale(Context context, String language) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
}
Upvotes: 2
Reputation: 3064
First, change values-ru-rRU to values-ru.
You can use this method to get resource
public Resources getCustomResource(String lang){
Locale locale = new Locale(lang);
Resources standardResources = activity.getResources();
AssetManager assets = standardResources.getAssets();
DisplayMetrics metrics = standardResources.getDisplayMetrics();
Configuration config = new Configuration(standardResources.getConfiguration());
config.locale = locale;
Resources res = new Resources(assets, metrics, config);
return res;
}
You can use it in your code like this
else if (LANGUAGE.equals("Russian"))
{
Resources res = getCustomResource("ru");
}
hope this help you.
Upvotes: 1