各位大家好!所以我尝试在我的应用程序中实现更改语言。我这样做如下: array.xml
<resources>
<string-array name="Language">
<item>English</item>
<item>Ukraine</item>
<item>French</item>
<item>Spanish</item>
<item>Italian</item>
</string-array>
<string-array name="languageAlias">
<item>"en_US"</item>
<item>"uk_UA"</item>
<item>"fr"</item>
<item>"es"</item>
<item>"it"</item>
</string-array>
</resources>
我有nessesary值-en,-fr,-es和我的字符串值... 我有SettingsActivity,SettingsFragment。 这是碎片:
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onStop() {
super.onStop();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.i("SettingsFragment", "key = " + key);
if (key.equals("list_preference")) {
Log.i("SettingsFragment", "key = "+ key);
setLanguage(getActivity().getApplicationContext(), key);
restartActivity();
}
}
private void setLanguage(Context context, String languageToLoad) {
String localeStr = getPreferenceScreen().getSharedPreferences().getString(languageToLoad, "");
if(localeStr.equals("en_US")){
Log.i("setLanguage", "en");
Locale locale = new Locale(localeStr);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
} else
if(localeStr.equals("uk_UA")){
Log.i("setLanguage", "uk");
Locale locale = new Locale(localeStr);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
}
private void restartActivity() {
Intent intent = getActivity().getIntent();
getActivity().finish();
startActivity(intent);
}
}
res / xml / setting.xml中的PreferenceScreen
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="PreferenceCategory">
<CheckBoxPreference
android:key="checkbox_preference"
android:title="CheckBoxPreference.title"
android:summary="CheckBoxPreference.summary" />
</PreferenceCategory>
<PreferenceCategory
android:title="PreferenceCategoryList">
<ListPreference
android:key="list_preference"
android:title="PreferenceCategoryList.title"
android:summary="PreferenceCategoryList.summary"
android:entries="@array/Language"
android:entryValues="@array/languageAlias"
android:dialogTitle="PreferenceCategoryList.dialogTitle" />
</PreferenceCategory>
但是,当我从列表中选择一种语言时,它可以正常工作,但是当您重新启动应用程序时,它将不会被选中。 还想问一下我选择的正确方法是否正确?可能有更好的方法吗?更新还是更正确?请分享与此主题相关的有用链接。
感谢您的关注,如果对此问题的描述表达不好,我很抱歉。