我有一個(或多或少)用其他語言翻譯的應用程序。爲此,我使用了locale
並保存用戶偏好的語言,我使用了SharedPreferences
。更改語言環境``onResume`方法後不工作?
使用此設置,我設法在應用程序內的任何/每個活動上加載首選語言。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick);
findViewById(R.id.flagcollection).setVisibility(View.GONE);
findViewById(R.id.worldmapswitch)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (flagWorld) {
// means true
findViewById(R.id.flagcollection).setVisibility(View.GONE);
flagWorld = false;
} else {
findViewById(R.id.flagcollection).setVisibility(View.VISIBLE);
flagWorld = true;
}
}
});
preferences = getSharedPreferences("settings_values", MODE_PRIVATE);
String SavedLocaleLang = preferences.getString("LocalLang", null);
Locale locale = new Locale(SavedLocaleLang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
....
的問題是,如果出於某種原因,我離開應用程序(不退出/結束活動),一段時間後,當我返回到應用程序,它運行使用手機的默認語言而不是保存的值語言環境。
然後,閱讀有關的onResume的奇蹟無數的職位,我的Java結合後無技能我嘗試這樣做:
@Override
public void onResume(){
super.onResume();
// put your code here...
preferences = getSharedPreferences("settings_values", MODE_PRIVATE);
String SavedLocaleLang = preferences.getString("LocalLang", null);
Locale locale = new Locale(SavedLocaleLang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
}
我以爲我已經解決了我的問題,但在更短的測試結果後,不到1小時,我意識到我什麼都沒做(至少沒有什麼好處)。我在某個地方做錯了什麼。
如果任何人有技能,耐心和很多善意,請幫助我瞭解我做錯了什麼和在哪裏。
任何幫助將不勝感激!請不要諷刺。在那裏,我做得很好:P
謝謝!
P.S.網友「Cochi」要求的代碼保存在Prefereces語言環境......所以在這裏你去:
findViewById(R.id.flaghungary)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String localeHU = "hu";
SharedPreferences settings = getSharedPreferences("settings_values", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("LocalLang", localeHU);
editor.apply();
Locale locale = new Locale("hu");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
setContentView(R.layout.activity_pick);
Context context = getApplicationContext();
Toast.makeText(context, "Magyar nyelv kiválasztva", Toast.LENGTH_SHORT).show();
recreate();
}
});
最有可能的,你的進程在你的應用在後臺時被終止。 [這是非常正常的](https://developer.android.com/guide/components/processes-and-threads.html#Lifecycle)。除此之外,請解釋「我做錯某個地方」的含義。 – CommonsWare
我最初的想法是,在保存區域設置時,是否在'SharedPreferences.Editor'對象上調用'commit()'或'apply()'?這是一個常見的疏忽,sharedPreferences不會被更新,除非你這樣做。 – DeeV
你好。感謝您的快速答覆。我已經更新了onCreate的代碼,就像以前一樣。現在我正在嘗試Nika Kurdadze的解決方案。也許它的工作原理:D – Robert