I want to write a application that can display either english or chinese. I have already prepared 2 string.xml which is value/strings.xml and value-zh-rHK/strings.xml. But I have no idea how to change the language via ListPreference of android.
xml/preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<SwitchPreference
android:key="pref_nightmode"
android:title="@string/nightmode"
android:defaultValue="false">
</SwitchPreference>
<ListPreference
android:key="pref_lang"
android:title="@string/lang"
android:dialogTitle="Choose Language"
android:entries="@array/lang"
android:entryValues="@array/lang_value"
android:defaultValue="@string/lang_default">
</ListPreference>
and the Preferences.java
public class Preferences extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(drawer_menu[5]);
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MainPreferenceFragment()).commit();
}
public static class MainPreferenceFragment extends PreferenceFragment {
String locale;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
PreferenceManager pm = getPreferenceManager();
ListPreference lang = (ListPreference) pm.findPreference("pref_lang");
if(lang.getValue().equals("English")) {
locale = "en_US";
} else {
locale = "zh_HK";
}
}
}
The activity extends BaseActivity because I have a drawer menu right there.
You can change language settings for app only. Use Locale class and update default configuration. Language change only applied when activity restart or re-start application. Use following locale class
Application class :
BaseActivity :
Above answer is taken from : Changing Locale within the app itself
Android Document : http://developer.android.com/reference/java/util/Locale.html