Change language in the app programmatically in Android [duplicate] - android

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Change app language programmatically in Android
I want to change language in my SettingsActivity.java for all Activities immediately.
And save this choice (even when I exit from app or reboot phone) regardless of system locale.
How can I do that?
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
switch (pos) {
case 0:
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext()
.getResources().getDisplayMetrics());
break;
case 1:
Locale locale2 = new Locale("de");
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;
getBaseContext().getResources().updateConfiguration(config2, getBaseContext()
.getResources().getDisplayMetrics());
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}

1) between exit app and reboot you can save choice like this:
Create Application class
public class MutawaApplication extends Application {
(http://developer.android.com/reference/android/app/Application.html)
register it in AndroidManifest.xml
android:name=".MyApplication"
In this class in onCreate read language from SharedPreferences. Save it to SharedPreferences when you change lang in app.
2) in your Activities check locale on onResume and if need make replaceContentView()

Related

Android app Locale language change not working for EN, but working for other languages

I am trying to add both FR and EN to my app, so I used the editor to translate the strings, thus creating a strings.xml(en-rGB) and a strings.xml(fr-fFR). I am using them inside of a spinner, so when I choose RO (default languade) or FR the string from all over the app change. But when I choose EN it doesn't change any string. I created both FR and EN simultaneously, so I cannot seem to find any difference between them, that might make the app not behave as I like.
The code where I switch between laguages:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TaraITEM clickedItem = (TaraITEM) parent.getItemAtPosition(position);
String clickedCountryName = clickedItem.getCountryName();
pozitie = position;
if(!clickedCountryName.equals(lastCountryName)) {
lastCountryName = clickedCountryName;
if (clickedCountryName.equals("FR")){
setLocale("fr");
recreate();
} else if (clickedCountryName.equals("EN")){
setLocale("en");
recreate();
}else if(clickedCountryName.equals("RO")){
setLocale("ro");
recreate();
}
}
}
And the list created, that I double-checked so there won't be any typo:
private void initList() {
mCountryList = new ArrayList<>();
mCountryList.add(new TaraITEM("RO", R.drawable.steag_ro));
mCountryList.add(new TaraITEM("EN", R.drawable.steag_en));
mCountryList.add(new TaraITEM("FR", R.drawable.steag_fr));
}
EDIT: addes setLocale method:
private void setLocale(String limba){
Locale locale = new Locale(limba);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale= locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
SharedPreferences.Editor editor = getSharedPreferences("Setare limba", MODE_PRIVATE).edit();
editor.putString("Limba mea", limba);
editor.putInt("Pozitie", pozitie);
editor.apply();
}
I have managed to solve this issue by adding another locale for RO because Android Studio has en as default language. So the source strings.xml file will be used as en locale. In my case, the default strings.xml had ro translations, so when I tried to use en, the app would use the default, so romanian translations.

Multi language android app during Runtime? [duplicate]

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.

How to reload the current view when I change the locale in app in android

I am currently work with changing language in the app. My app structure is tab host + fragment I have successfully change the locale but it is quite strange.
That means after I run the change locale code , it does not change the view immediately but only when I go to another tab. I think this is due to I need to reload the view, but are there any way to implment this without kill and restart the activity?
Because there is some goolge analytic code, the entry number will be increase if the user start activity again? Are there standard way to reload view? thanks
The change locale function is in one of the tabhost fragment, I have to refresh the view in tabhost (main activity), and the current fragment .
public OnClickListener setChangeLangListener(final String lang) {
OnClickListener changeLangListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
Configuration config = new Configuration(getResources()
.getConfiguration());
if (lang.equals("en")) {
config.locale = Locale.ENGLISH;
chi.setTextColor(oldColor);
eng.setTextColor(getActivity().getResources().getColor(android.R.color.white));
} else {
config.locale = Locale.TRADITIONAL_CHINESE;
eng.setTextColor(oldColor);
chi.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}
getResources().updateConfiguration(config,
getResources().getDisplayMetrics());
}
};
return changeLangListener;
}
eng.setOnClickListener(setChangeLangListener("en"));
chi.setOnClickListener(setChangeLangListener("zh"));
Allright add this to your manifest
android:configChanges="locale"
and override onConfigurationChanged() in your activity
#Override
public void onConfigurationChanged(Configuration newConfig) {
// refresh your views here
super.onConfigurationChanged(newConfig);
}
go here for more info.
Hope it helps. :)
Have you tried calling setContentView. Eg.:
String languageToLoad = "fr"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
activity.setContentView(R.layout.your_layout);

Changing android application language [duplicate]

This question already has answers here:
Change app language programmatically in Android
(34 answers)
Closed 9 years ago.
In my app I have a special menu where I can change application language.I get labels from project API(by parsing JSON) and project values xml.Can I change android application language without restart of application and сhangibg system language.
Insert this method and call it for changing the language.
private void setLocale (String localeCode , Bundle b ){
Log.d(TAG+"set location function: "+localeCode);
locale = new Locale(localeCode);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
getApplicationContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
UserDetail.this.getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
onCreate(null);
}
On toggle change or any selection call value like this:
setLocale("en-us",savedInstanceStat); // for english
setLocale("ar",savedInstanceStat); // for arabic
you can use toggle button to change language and set your selected language programamtically in your app without close app.
1.you will check which language selected?
String prefsToogleStr = getSharePrefrenceLocale();
Log.d("tag", "CtrlDashBoard prefsToogleStr" + prefsToogleStr);
if (prefsToogleStr.equalsIgnoreCase("en")) {
toggleLocaleButton.setChecked(true);
CommonMethod.setLocale("en", viewDashBoard);
} else {
CommonMethod.setLocale("ur", viewDashBoard);
toggleLocaleButton.setChecked(false);
}
////////////////////////////////////////
public String getSharePrefrenceLocale() {
SharedPreferences prefs = viewDashBoard.getSharedPreferences(
viewDashBoard.getPackageName(), ViewDashBoard.MODE_PRIVATE);
return prefs.getString("locale", "en");
}
2.change language in toggle button check change listener:
// Locale Toogle
toggleLocaleButton
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (buttonView.isChecked()) {
setSharePrefrenceLocale("en");
CommonMethod.setLocale("en", viewDashBoard);
} else {
setSharePrefrenceLocale("ur");
CommonMethod.setLocale("ur", viewDashBoard);
}
dialog.dismiss();
}
});
}
/////////////////////////////////////
public void setSharePrefrenceLocale(String locale) {
SharedPreferences prefs = viewDashBoard.getSharedPreferences(
viewDashBoard.getPackageName(), ViewDashBoard.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("locale", locale);
editor.commit();
}
//////////////////////////////////////
Main Method:call
public static void setLocale(String localeName, Context context) {
Locale locale = new Locale(localeName);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config,
context.getResources().getDisplayMetrics());
}
i hope you understand .this is useful to you.

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