I have an app where the user can change its language.
Everything is working fine, with just this code on my MainActivity.onCreate():
String lang = PreferenceManager.getDefaultSharedPreferences(this).getString("languagePref", "default");
Configuration config = getResources().getConfiguration();
if( lang.equals("default") ) lang = Locale.getDefault().getLanguage();
config.locale = new Locale(lang);
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
When I restart the app or navigate through activities it's still in the right language.
The only problem is on the PreferenceActivity screen. When the orientation changes, the PreferenceActivity title (and only it) changes to the default device language.
The prefs are still checked correctly, if I go back (closing the PreferenceActivity) the app is still on the right language, but the PreferenceActivity stays wrong until I restart the app.
I tried forcing the code above on the PreferenceActivity.onCreate() and altough debugging seems OK, the PrefenceActivity Title stays wrong.
Here's my PrefenceActivity code:
public class PreferencesActivity extends PreferenceActivity {
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
This behavior doesn't happen on any other Activity :/
Locking the screen orientation is not an option.
Any thoughts?
Thanks.
OK, this fixed it for me.
#Override
protected void onSaveInstanceState(Bundle outState) {
String lang = PreferenceManager.getDefaultSharedPreferences(this).getString("languagePref", "default");
Configuration config = getResources().getConfiguration();
if( lang.equals("default") ) lang = Locale.getDefault().getLanguage();
config.locale = new Locale(lang);
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
super.onSaveInstanceState(outState);
}
I solved this problem using onConfigurationChanged().
In this method I'm saving preferred language again in Configuration object.
OnCreate method of activity is called when orientation is changes, so some property is again set by your code, look at your on oncreate method or lock your screen orientation.
You can lock your screen orientation to your activity by Using
android:screenOrientation="portrait"
or
android:screenOrientation="landscape"
Related
I'm trying to implement app language switch on the runtime, once the user made language changes in app preferences. I have this code in my PreferenceFragment:
public class Fragment_Preferences extends PreferenceFragment {
private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
Log.i("Pref changed", "Settings key changed: " + key);
if(key.equals("language_preference"))
{
String system_language = Locale.getDefault().getLanguage().toUpperCase();
String preference_language = Common_Methods.get_preference_language(getActivity());
Toast.makeText(getActivity(), "Pref changed: "+preference_language, Toast.LENGTH_SHORT).show();
Common_Methods.set_app_interface_language(getActivity(), system_language, preference_language);
}
}
};
prefs.registerOnSharedPreferenceChangeListener(prefListener);
}
}
This is my set_app_interface_language method in Common_Methods class:
public static void set_app_interface_language(Context context, String system_language, String preference_language)
{
if(!preference_language.equals(system_language))
{
Locale locale = new Locale(preference_language.toLowerCase());
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
}
I get the Toast message when I change language in preferences. I know that this method works since I call it also from my Fragment_Main. But the language doesn't change on the runtime - I have to exit the app and reopen it, only then I see the changes.
So how can I make the app language change on the runtime, without restarting the app? Thanks!
OK, I think I solved this problem: I call for Common_Methods.set_app_interface_language not in SharedPreferences.OnSharedPreferenceChangeListener, but rather in onRestart method of my Fragment_Main.
I also changed set_app_interface_language to return new config. And once it's returned - I pass it to onConfigurationChanged method to recreate fragment. Now, I did ran into Performing pause of activity that is not resumed... error message once my device's screen turned off. After googling a little about it, I realized that it's non-fatal exception, but I still used Handler to postpone recreate() for 1 millisecond and let the Fragment restart properly. I also set another method in my Common_Methods to check if there were any changes made to the app language and recreate the fragment only if the method returns true; I call this method in onRestart That gave the app some performance boost, since now there's no need to recreate the fragment every time the app restarts.
I'm developing an application for android and when everything should be finished I've found an extrange behaviour. In some devices the screen starts to flicker, and there is no apparent reason for that. It may happen in initial splash with only an AsyncTask quering a webservice or in the home screen with no asynctask at all.
It's strange because only happens in devices with android 4.2, nor in 2.3 or 2.2. I've tried enabling the tag harware-accelration in manifest but I've no clue for what can be the reason
Some help?
Thanks in advance.
Finally I've managed how to avoid this. Here was the trick, just changing my Application's Override OnConfigurationChanged.
This was my old code
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Locale l = getLocale();
Configuration config = new Configuration(newConfig); // get Modifiable Config from actual config changed
config.locale = l;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
and I've changed to this
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Locale l = getLocale();
Configuration config = new Configuration(newConfig); // get Modifiable Config from actual config changed
config.locale = l;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
I hope someone finds this useful.
I have to change the language on runtime in Android (yes, I know that this is not a good behaviour, but this is a requirement...).
So I have a basic class, from which every activity extends. This class has the following function:
public static void changeLanguage(Context context) {
Resources res = context.getResources();
/*
* Change locale settings in the app.
*/
DisplayMetrics dm = res.getDisplayMetrics();
/*
* Store and load data in this preferences
*/
android.content.res.Configuration conf = res.getConfiguration();
String[] localArray = res.getStringArray(R.array.language_short_array);
if (localArray != null) {
SharedPreferences settings = context.getSharedPreferences(
MyService.APP_ID, MODE_PRIVATE);
conf.locale = new Locale(localArray[settings.getInt(
PREFERED_LANGUAGE_KEY, 0)]);
res.updateConfiguration(conf, dm);
}
}
I will call this method in onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
changeLanguage(this);
}
This is in the super-class. My Activities extends from it and call super.onCreate at first. After this call, they set their layout and initializes their settings...
I thought that my lines of code would make it. But I have the following problem: Sometimes, the activity changes the language and sometimes not!
If I set a debug breakpoint on it and after the programm pauses I press continue, everything works fine. So I think, in some cases, where my Application is "slow enough", the language will change correctly, whereas the language won't change if the application is too fast...
Is there any solution of my problem? How can I be sure, that my language will change correctly in any time?
Thanks a lot!
Edit: Here is an example for a class which extends from my super-class
public class MainMenuActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
}
changeLanguage(this); only needs to be called when the language has changed or when the App is loaded.. res.updateConfiguration(conf, dm); updates the global config and is specific to your app instance not your activity instance.
When you change the locale in an Activity you have to recreate that Activity to see your language change. This can be easily done by forcing an orientation change then forcing it back like this:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
If you hit back after a language change you will see the old language because onCreate is not called. You will have to detect in onResume that the language changed and force a recreate of the Activity.
-= EDIT =-
Using Screen Orientation to reload the Activity has proven to be a bit buggy on some devices. I am now using this to reload the current Activity:
public static void resetScreen(Activity activity) {
if (activity != null) {
if (Build.VERSION.SDK_INT >= 11) {
activity.recreate();
} else {
Intent intent = activity.getIntent();
activity.overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.finish();
activity.overridePendingTransition(0, 0);
activity.startActivity(intent);
}
}
}
I think you need to post an example of an Activity that extends your superclass. Calling changeLanguage in onCreate() seems suspicious to me, though. That's only going to run when the app is first initialized. To change the language once your app is loaded, you'd have to stop it and re-create it.
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!)
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.