I have created 4 languages for the app. I can change the Lauaguage, ok, but if close the app and then start I it again, the app starts atfirst with the default string.xml.
How to let the app starts with the last selected Language ?
should I call the the methode by OnCreate in the mainActivity ?
#SuppressWarnings("deprecation")
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
DisplayMetrics dm = getResources().getDisplayMetrics();
Configuration conf = getResources().getConfiguration();
conf.locale = myLocale;
getResources().updateConfiguration(conf, dm);
Intent refresh = new Intent(this, Languages.class);
startActivity(refresh);
/* "en" = English
"hi" =Hindi
"fr" =French
"it" =Italian
"de" =German
"es" =Spanish
"ja" =Japanese
"ko" =Korean
"nl" =Dutch
"pt" =Portuguese
"ru" =Russian
"zh" =Chinese
"ar" = arabic
*/
}
How can the user change the default language ?
Why don't you store the selected language in shared preferences? That way you can always check for the selected language when your app starts, and then load the appropriate language file.
I have used a long Way like below but it works. Thanks :
OnResume :
selected_lang= myshared.getString("selected_lang","de");
lang_found= Integer.parseInt(myshared.getString("lang_found","0"));
setLocale(selected_lang);
#SuppressWarnings("deprecation")
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
DisplayMetrics dm = getResources().getDisplayMetrics();
Configuration conf = getResources().getConfiguration();
conf.locale = myLocale;
getResources().updateConfiguration(conf, dm);
if(lang_found==0) {
Intent refresh = new Intent(this, MainActivity.class);
startActivity(refresh);
lang_found=1;
}
#Override
protected void onDestroy() {
lang_found=0;
Save_setting();
super.onDestroy();
}
Related
I am trying to change app localization at runtime it working correctly but when clear app from memory and reopen it again I find that resources like strings.xml and styles.xml take the default mobile language!
See my method to localize the app:
I created an abstract class like below:
public abstract class BaseLocalization extends AppCompatActivity {
SharedPreferences preferences;
Constants constants;
String currentLocale = "en";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
constants = new Constants();
preferences = getSharedPreferences(constants.getPreferences(), MODE_PRIVATE);
currentLocale = preferences.getString(constants.getLocale(), "en");
setLocale(currentLocale);
}
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
}
After doing this, I made all the classes which extended AppCompatActivity extend this class. And saved the locale in SharedPreferences. And the locale is persisted until the app data is cleared/uninstalled.
My app language is turkish and device language is english. I can set the language turkish with code below smoothly. All application pages change properly.
private void changeLang(String locale) {
Resources res = this.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.setLocale(new Locale(locale.toLowerCase()));
res.updateConfiguration(conf, dm);
Configuration newConfig = new Configuration();
newConfig.locale = new Locale(locale.toLowerCase());
onConfigurationChanged(newConfig);
}
But when Im sending a push notification, Notification text still english. I see the locale still english when Im debug.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Locale current = getResources().getConfiguration().locale;
//current not change, always english
}
}
Why the service cannot get true locale, always get device locale.
I have a method that translates my application from English to Swedish and back again if the user so wishes. However, I don't really like the fact that the activity restarts every time because it's giving me a hard time with the savedInstaceState and I've had several crashes because of this.
Here's how my method that changes language looks:
public void setApplicationLanguage(String language) {
myLocale = new Locale(language);
Resources res = activity.getResources();
DisplayMetrics display = res.getDisplayMetrics();
Configuration configuration = res.getConfiguration();
configuration.locale = myLocale;
res.updateConfiguration(configuration, display);
Intent refresh = new Intent(activity, StartupActivity.class);
activity.startActivity(refresh);
}
Is there any chance that the same function can be applied without the:
Intent refresh = new Intent(activity, StartupActivity.class);
activity.startActivity(refresh);
?
Try this
I also had this issue.I used the code below and then it changed the language without refreshing the activity
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
onConfigurationChanged(conf);
/*Intent refresh = new Intent(this, AndroidLocalize.class);
startActivity(refresh);*/
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// refresh your views here
lblLang.setText(R.string.langselection);
super.onConfigurationChanged(newConfig);
// Checks the active language
if (newConfig.locale == Locale.ENGLISH) {
Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
} else if (newConfig.locale == Locale.FRENCH){
Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
}
}
declare in Manifest android:configChanges="locale"
You can replace the code:
Intent refresh = new Intent(activity, StartupActivity.class);
activity.startActivity(refresh);
With the method from Activity class:
recreate();
I hope your minimum SDK version will support because it was introduce in SDK 11. Your activity will be recreate as a new instance remember! Everything will be started afresh. From my experience it is fast compared to making a new Intent. But if you want to pass some data the method of using Intent is better than that! You can add extras to the Intent.
Create a singleton class:
public class Singleton {
private static Singleton mInstance = null;
private int repeat = 0;
public int getRepeat() {
return repeat;
}
public void setRepeat(int repeat) {
this.repeat = repeat;
}
}
Now you have a method that you can set and get the data, so make a method and put it under onResume() method, call your method and you can get and set the data like this:
Singleton.getInstance().setRepeat(1);
Singleton.getInstance().getRepeat();
This question already has answers here:
Change app language programmatically in Android
(34 answers)
Closed 2 years ago.
My aim is to change an application language from English to Chinese during runtime, is there any suggestions?
language_spinner = (Spinner)findViewById(R.id.settings_language_spinner);
language_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (pos == 1){
Toast.makeText(parent.getContext(),"You have selected English",Toast.LENGTH_SHORT).show();
setLocale("en");
}else if (pos == 2){
Toast.makeText(parent.getContext(),"You have selected Chinese",Toast.LENGTH_SHORT).show();
setLocale("zh");
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (!conf.locale.getLanguage().equals(lang)) {
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, SettingsActivity.class);
startActivity(refresh);
finish();
}
}
This code is working properly with English but not working with Chinese
please help me in finding the solution ..
I can give you idea how you can implement this:
step 1: make string file for all texts in values directory as string-ch, ch is the code for Chinese language. and in code get every string with the getResources.getString(R.string.text_name); so that it can take string value at run time either English or Chinese.
step 2: now create method :
void changeLanguage(String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
step 3: call this method where you want to change language suppose if you want to get changed language of you application according to device language then you can call as:
changeLanguage(Locale.getDefault().getLanguage());
Create below function in Util like class
public static void setLocale(Activity activity, String languageCode) {
Locale locale = new Locale(languageCode);
Locale.setDefault(locale);
Resources resources = activity.getResources();
Configuration config = resources.getConfiguration();
config.setLocale(locale);
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
Call this function from activity at the start. The original post with this code snippet can be found at Change app language programmatically in Android page.
I want to let the user change the language of my application using spinner (or any way).
I tried many ways but they change the language of this activity not all activities, and I want to save it so when the user restart the app he will find the last choosed language.
you can use this code in spinner or any way you want
String languageToLoad = "en"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
then you should save the language like this
SharedPreferences languagepref = getSharedPreferences("language",MODE_PRIVATE);
SharedPreferences.Editor editor = languagepref.edit();
editor.putString("languageToLoad",languageToLoad );
editor.commit();
and use the same code in every activity in onCreate() to load the languageToLoad from the SharedPreferences
This is an old question, but I'll answer it anyway :-)
You can extend Application class to apply Abol3z's solution on every Activity. Create class:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String lang = preferences.getString("lang", "en");
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
}
And set MyApplication as application class in manifest:
<application
android:name=".MyApplication"
...
/>
You can set the lang value (in your spinner):
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
preferences.edit().putString("lang", "en").commit();
Use SharedPreferences to keep track of the language the user chose, and then set the activities to use that language in the onCreate (), and maybe onResume() method. This way it will persist across app restarts etc.
btnChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
//preferences.edit().putString("lang", "bn").commit();
String lang = preferences.getString("lang", "en");
//Log.e("lang", "lang in Main Activity:"+lang);
if (lang.equalsIgnoreCase("en")){
setLocale("bn");
preferences.edit().putString("lang", "bn").commit();
btnChange.setText("Eng");
}else if(lang.equalsIgnoreCase("bn")){
setLocale("en");
preferences.edit().putString("lang", "en").commit();
btnChange.setText("বাংলা");
}
}
});
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, MainActivity.class);
startActivity(refresh);
finish();
}
we use two language for test purpose. keep all string in different folder named values and values-bn.