Reputation: 3026
I'm trying to add language controller meaning changing the language of my app.
I've added 4 flags (ImageView), and whenever I press the flag I want, I want the app to change the language depennding on that flag.
The apps start out being English, and when I press the Danish falg, the language DOES switch to Danish, but whenever I want to change back to english, nothing happens.
I've made several strings.xml files in their own value folder
value-en/strings.xml
value-dk/strings.xml
Method changing language:
english.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config,getResources().getDisplayMetrics());
setContentView(R.layout.activity_main);
}
});
english
is my variable for the ImageView
Upvotes: 1
Views: 1747
Reputation: 301
I tested below code and it is working as per my consideration. Check this it will help you or not. Call this method on your click listener and pass locale string as a parameter.
private void setDeviceDefaultLanguage(String languageToLoad) {
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config,
getResources().getDisplayMetrics());
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
Upvotes: 0
Reputation: 3026
I found my solution.
In order to save the onClickListener()
on my other components, I need to refresh the activity, posted below:
To restart the activity
I simply made a method like the one below:
//Restarts the activity after changing the languagse
private void RestartActivity(){
Intent intent = getIntent();
finish();
startActivity(intent);
}
And everytime I change the language, I run the method:
english.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config,getResources().getDisplayMetrics());
setContentView(R.layout.activity_main);
RestartActivity(); //Run the method as the last thing
}
});
For some reason the listeners doesn't see mto stay, but this solution works for me.
Upvotes: 1