How to implement localization from fragment? - android

I am switching application language English to Arabic and vice versa from a fragment.
The code below works, it loads the values-ar\strings.xml and the language is changed from english to arabic. The app's UI elements doesn't change immediately based on the updated language settings, RTL alignment. The change is only reflected when application is closed and reopened.
Locale locale = new Locale("ar");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getActivity().getResources().updateConfiguration(config, getActivity().getResources().getDisplayMetrics());
getActivity().recreate()

It worked, add this to the activity holding the fragment and call it instead of getActivity().recreate().
public void restartActivity() {
Intent intent = getIntent();
finish();
startActivity(intent);
}

Add this line in the manifest file.
android:configChanges="locale|orientation"

Related

Android developer change all app screens language on button click

I know how to use locale and strings.xml for global locale, in addition I created 3 buttons on rhe main activity with 3 different languages on them, how can I switch the whole strings in all screens in one click, how can I do that?
Step1:
Use a preference to store the locale language and country, if you want this language switching is persistent.
Step2:
Try a function like this
public void switchLocale(Locale locale) {
Configuration config = getBaseContext().getResources().getConfiguration();
if (locale != null && !config.locale.equals(locale)) {
Locale.setDefault(locale);
Configuration conf = new Configuration(config);
conf.locale = locale;
getBaseContext().getResources().updateConfiguration(conf,
getBaseContext().getResources().getDisplayMetrics());
}
}
Step3:
Restart your current activity.
Hope this helps.

Clicking a button to switch the language

When I click on the "sub_changelang" button, it should change the program language to French for example. I got the following code to change the locale but I have no idea how to refresh/ pdate the app to change the language to French.
Button cl = (Button) findViewById(R.id.sub_changelang);
cl.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Locale locale = new Locale("fr_FR");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
}
});
It doesn't work. How can I fix it? I tried to add:
MainActivity.this.getResources().updateConfiguration(config, MainActivity.this.getResources().getDisplayMetrics());
but it didn't work. I also tried:
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
and it didn't work either.
android:configChanges="locale"
is set inside the AndroidMainfest.xml under application -> activity
I am using this code to set locale
String languageToLoad = "fr_FR";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config,context.getResources().getDisplayMetrics());
Intent intent = new Intent(XYZ.this, XYZ.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
here context is application Base Context.
Please also try "fr" instead of "fr_FR" because I am working for Arabic locale and its working fine.
You need to restart your Activity after changing locale.
You can use activity.this.recreate().But it will support from API level 11.

getResources().getString() doesn't work after orientation has been changed

My android application is in dual language. So I have 2 res folder value and value-sw(for swahili). I am fetching string values from this file in design and also at run time. For example in layout:
android:hint="#string/Officer"
and in code:
getResources().getString(R.string.Officer);
To change the locale setting I have function which I call on onCreate() which looks like this:
public void ChangeLanguage(Context ctx,String Language){
Resources res = ctx.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration config = res.getConfiguration();
config.locale = new Locale(Language.toLowerCase());
res.updateConfiguration(config, dm);
}
All works fine. Problem comes only if I change the orientation.
For example on start up I set the language to Swahili. So everything is in Swahili. Now if I change the orientation from vertical to horizontal or vice-verse. Textbox box hint which was set in layout remains in Swahili which I expect. But getResources().getString(R.string.Officer); fetches value from the default value file, which is English.
Any suggestions?
Set android:configChanges="orientation" to your activity in AndroidManifest.xml
Doing so will cause your activity not to be destroyed and re-created when orientation is changed.
The problem with having the android:configChanges attribute, is that that disables onCreate() from being called after an orientation change. You are basically telling the app: "I know there will be orientation changes, so don't recreate the screen, I will handle it"
I would suggest calling that function of yours in the onConfigurationChanged() method. Have in mind that any views will be null at that point, so if you need them you will need to get a new reference.
I have same case as one in the question, using English and Swahili in an app.
This is how I tackled it : I created a folder called values-sw then in the folder I created a resource file named string.xml. this is where all my Swahili translations are written. I call the following method in onCreate:
public static void setLocale(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
String userLocale = sharedPreferences.getString("userlocale", null); // adapt to your need
if (userLocale != null) {
Locale locale = new Locale(userLocale);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
}
Dont forget to refresh your activity for changes to take effect:
finish();
startActivity(getIntent());
(I know it's pretty late for this answer I hope it helps someone out there, cheers!)

Set-up the application Language in Android Preferences

I would like the application language to be set according to the user preferences but up till now it doesn't work how I would like it to.
I have set the default values: strings.xml and also values-es with a strings.xml inside in spanish. I have a menu option which brings the user to a Preference activity where he can amon gother things chose the language.
So here are some extracts of the code:
public class Preference extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
......
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
...}
//(......)
//and here I have the listener so when the language pref changes value the locale gets changed.
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("listPref2")) {
String idioma = sharedPreferences.getString("listPref2", "catala");
if ("castella".equals(idioma)) {
idioma = "es_ES";
Locale locale = new Locale(idioma);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getApplicationContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
}
}
So when I change the language it works but then when I come back later or restart the emulator the language gets back to default locale the en_US and the app language gets changed back to default again. What can I do to sort that out?
I know I can get this preference (which I can access to from all my activities) and then each time set up the locale but I find it a bit heavy isn't there a way to do it in a more elegant way?
What I would like to do is if the user sets up the language so when he comes back 2 days later he doesn't have to change the language again.
Any ideas?
OK it may help someone. I have added the folowing to the main activity manifest:
android:configChanges="locale"
Then when the user choses the preferences I have put a confirm button and then this button brings you to main activity that is why the lnagages gets reset.
I have a static class where I have this code to change the locale:
public static void updateLanguage(Context context, String idioma) {
if (!"".equals(idioma)) {
if ("castella".equals(idioma)) {
idioma = "es_ES";
} else if ("catala".equals(idioma)) {
idioma = "ca_ES";
}
Locale locale = new Locale(idioma);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, null);
}
}
end at every activity I have like 20 of them I call this method before:
setContentView(R.layout.list_event);
With these methods when I rotate the screen the activities don't change the language
here is a link to a blog that helped me:
http://adrianvintu.com/blogengine/post/Force-Locale-on-Android.aspx
I would think that you need to be setting the locale in the MainActivity onCreate method. The same way you are setting it when the onSharedPreferenceChanged method.

Changing locale: Force activity to reload resources?

So I have a language setting in my application. When the language is switched, I would like all the textviews etc to change language immediately. Currently I just change the locale in the configuration, so the language has changed when the user restarts the activity.
An ugly solution to my problem would be to make each textview load the new resources each time the language is changed. Is there a better solution? Perhaps a neat way to discretely restart the activity? Or maybe just force reload of the resources?
In your AndroidManifest.xml, add this attribute to your Activity
android:configChanges="locale"
In your activity override onConfigurationChanged()
#Override
public void onConfigurationChanged(Configuration newConfig) {
// refresh your views here
super.onConfigurationChanged(newConfig);
}
https://developer.android.com/guide/topics/manifest/activity-element.html#config
I think the question is switching language in runtime for the app and displaying localized messages in UI. android:configChanges="locale" calls onConfigurationChanged if the system locale is changed (in setting of your device) while the app is running, and not if you change locale in the code for your app, which I guess is what you want to accomplish. That's why it's not refreshing.
Here is the method I use during every activity onCreate() or onResume() depending on my needs (if my activity will be resuming after user changed language settings or will always be created with language already set):
From there I just refresh the view manually or from onConfigurationChanged() which get called after this method finishes.
public static void changeLocale(Activity activity, String language)
{
final Resources res = activity.getResources();
final Configuration conf = res.getConfiguration();
if (language == null || language.length() == 0)
{
conf.locale = Locale.getDefault();
}
else
{
final int idx = language.indexOf('-');
if (idx != -1)
{
final String[] split = language.split("-");
conf.locale = new Locale(split[0], split[1].substring(1));
}
else
{
conf.locale = new Locale(language);
}
}
res.updateConfiguration(conf, null);
}
I'm not sure why this isn't picked up by onConfigurationChanged().
Hey, sandis, do you mean the method onConfigurationChanged() doesn't called in your activity when you changed the language? I met the same problem. The problem maybe this: when we change the language, the activity goes to onDestroy()(you can try this), so there is nobody to call onConfigurationChanged(). When we launch the activity again, the onCreate() is called, not the onConfigurationChanged(). There maybe something different in locale change and orientation change.
public void settingLocale(Context context, String language) {
Locale locale;
Configuration config = new Configuration();
if(language.equals(LANGUAGE_ENGLISH)) {
locale = new Locale("en");
Locale.setDefault(locale);
config.locale = locale;
}else if(language.equals(LANGUAGE_ARABIC)){
locale = new Locale("hi");
Locale.setDefault(locale);
config.locale = locale;
}
context.getResources().updateConfiguration(config, null);
// Here again set the text on view to reflect locale change
// and it will pick resource from new locale
tv1.setText(R.string.one); //tv1 is textview in my activity
}
Assuming you're changing the language through something like
private void updateLocale(#NonNull final Context context,
#NonNull final Locale newLocale) {
final Resources resources = context.getResources();
final DisplayMetrics displayMetrics = resources.getDisplayMetrics();
final Configuration configuration = resources.getConfiguration();
configuration.locale = newLocale;
resources.updateConfiguration(configuration, displayMetrics);
Locale.setDefault(newLocale);
}
You'll need to call Activity.recreate() in all currently open activities, which is what would happen if the user changed the system language while you were not subscribing to android:configChanges="locale".

Categories

Resources