Multi language android app during Runtime? [duplicate] - android

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.

Related

should the app first start with the default language?

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();
}

Android - Change app locale manually on button click

I want to change the application's Locale (language) to change programmatically when user wants to switch between Hindi and English using change language button.
I have a code to change language in place but it works only when I call in in the onCreate() of an activity before setContentView() method.
Any help is much appreciated.
See here my answer
Android Font in more then one langauge on single screen
for example if you want your application to support both English
and Arabic strings (in addition to the default strings),
you can simply create two additional
resource directories called /res/values-en (for the English strings.xml) and
/res/values-ar (for the Arabic strings.xml).
Within the strings.xml files, the
resource names are the same.
For example, the /res/values-en/strings.xml file could
look like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello in English!</string>
</resources>
Whereas, the /res/values-ar/strings.xml file would look like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">مرحبا في اللغة الإنجليزية</string>
</resources>
also , the /res/values-ur_IN/strings.xml file would look like this for urdu:
ur_IN for india ur_PK for pakisthan
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">انگریزی میں خوش!!</string>
</resources>
A default layout file in the /res/layout directory that displays the string refers to the
string by the variable name #string/hello, without regard to which language or directory
the string resource is in.
The Android operating system determines which version of
the string (French, English, or default) to load at runtime.A layout with a TextView control
to display the string might look like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/hello" >
</LinearLayout>
The string is accessed programmatically in the normal way:
String str = getString(R.string.hello);
For change the language you need to like that change lang..
btn_english.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, getResources().getString(R.string.lbl_langSelectEnglis), Toast.LENGTH_SHORT).show();
}
});
btn_arbice.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Locale locale = new Locale("ar");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, getResources().getString(R.string.lbl_langSelecURdu), Toast.LENGTH_SHORT).show();
}
});
btn_urdu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Locale locale = new Locale("ur_IN");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(HomeActivity.this, getResources().getString(R.string.lbl_langSelectEnglis), Toast.LENGTH_SHORT).show();
}
});
Try this function when click button.
public void changeLocale()
{
Resources res = getResources();
// Change locale settings in the app.
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale("hi_IN");
res.updateConfiguration(conf, dm);
setContentView(R.layout.xxx);
}
Use SharedPrefrences to save the user prefrences and call locale in onStart() not on onCreate(). This worked fine for me
Define DEFAULT value, so that your app wont cash
public static final String Default="en"; //so if value isn't found then english language will be used.
protected void onStart() {
SharedPreferences sharedPreferences = this.getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
String pine = sharedPreferences.getString("language", DEFAULT);
String languageToLoad = pine;
Locale locale = new Locale(languageToLoad);//Set Selected Locale
Locale.setDefault(locale);//set new locale as default
Configuration config = new Configuration();//get Configuration
config.locale = locale;//set config locale as selected locale
this.getResources().updateConfiguration(config, this.getResources().getDisplayMetrics());
invalidateOptionsMenu();
setTitle(R.string.app_name);
super.onStart();
}
Where I set sharedPrefrences value to hindi or english as per user choice. I used switch in this case. below you can see code.
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (aSwitch.isChecked()) {
SharedPreferences hisharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor hieditor = npsharedPreferences.edit();
npeditor.putString("language","hi");
npeditor.commit();
aSwitch.setChecked(true);
Toast.makeText(Settings.this, "Hindi Language Selected", Toast.LENGTH_LONG).show();
} else {
SharedPreferences ensharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor eneditor = ensharedPreferences.edit();
eneditor.putString("language","en");
eneditor.commit();
Toast.makeText(Settings.this, "English Language Selected", Toast.LENGTH_LONG).show();
aSwitch.setChecked(false);
}
}
});
Hope this helped!! Feel free to ask me if you got stuck in any step!!
You can refresh activity as below sample to change user interface after updating locale language of app on click of button:
OnButtonClicked(){
//it will check for android version.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
//after setting language it will update ui
refreshActivity();
}
public void refreshActivity() throws Exception {
try {
// refresh activity for language changes
Intent intent = getIntent();
YOUR_ACTIVITY_NAME.this.finish();
System.out.println("activity finished");
startActivity(intent);
System.out.println("starting activity");
} catch (Exception e) {
Log.d("RegistrationForm", "application crashed...");
e.printStackTrace();
}
}
#TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
context.getResources().updateConfiguration(configuration,
context.getResources().getDisplayMetrics());
return context.createConfigurationContext(configuration);
}
#SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale);
}
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
Complete Steps:
On button click check Android Version if Android version is below N then it will execute legacy code for locale language change that is updateResourcesLegacy. Else if Android Version is N or above N then it will execute updateResources() method.
After setting language refresh activity by calling refreshActivity() method, this method will update the user interface.

Change language in the app programmatically in Android [duplicate]

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()

Android how to change the application language at runtime

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.

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