[英]How to change language locally in portrait AND landscape mode
我必須實現一個應用程序原型,該原型應該可以更改應用程序內部的語言。 我的代碼:
...builder.setItems(langList, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectedLanguage = which;
if (selectedLanguage != -1) {
Configuration configuration = new Configuration(getResources().getConfiguration());
String currentLanguage = configuration.locale.getLanguage();
switch (selectedLanguage) {
case 0:
if (currentLanguage.equalsIgnoreCase("de")) {
configuration.locale = Locale.ENGLISH;
} else {
return;
}
break;
case 1:
if (currentLanguage.equalsIgnoreCase("en")) {
configuration.locale = Locale.GERMAN;
} else {
return;
}
break;
default:
break;
}
getResources().updateConfiguration(configuration, null);
Intent intent = new Intent(getActivity(), DashboardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
dialog.dismiss();
}...
而且效果很好。 但是問題是-更改顯示模式(縱向<=>橫向)時,會再次加載當前系統語言(分別在values文件夾中的strings.xml )。 有沒有人已經使用過它,或者有建議我該如何解決這個問題?
提前致謝..
您可以在用戶選擇其語言時將其保存在首選項中,並在oncreate方法中檢查首選項是否具有語言價值(如果未加載默認語言)
默認情況下,更改方向將調用oncreate方法,因此可以隨意在其中添加檢查代碼
您會疑惑地知道何時發生方向更改,因為發生了onConfigurationChanged()生命周期事件。
有關如何檢測方向變化的信息,請參見以下示例。 http://techblogon.com/android-screen-orientation-change-rotation-example/
當配置更改時,您可以存儲所需的任何值。 請注意,您也可以在首次設置值時將其存儲在設置中。
創建活動(onCreate())時,您可以讀取方向並設置任何適當的值。
總而言之,回顧一下活動生命周期,可以觸發一些相關事件。
所以,我使用SharedPreferences解決了這個問題:
... default:
break;
}
SharedPreferences preferences = getActivity().getSharedPreferences("SETTINGS_FILE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("currentLanguage", configuration.locale.getLanguage());
editor.commit();
getResources().updateConfiguration(configuration, null); ...
然后我在MainActivity / MainFragment中實現了方法setCurrentLanguage() :
... protected void setCurrentLanguage() {
Configuration configuration = new Configuration(getResources().getConfiguration());
SharedPreferences preferences = getSharedPreferences("SETTINGS_FILE", Context.MODE_PRIVATE);
String restoredLanguage = preferences.getString("currentLanguage", null);
if (restoredLanguage.equalsIgnoreCase("en")) {
configuration.locale = Locale.ENGLISH;
getResources().updateConfiguration(configuration, null);
}
} ...
最后我在setContentView(...)之前的每個活動/片段中都調用此方法:
// in an activity
... protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCurrentLanguage();
setContentView(R.layout.activity_dashboard); ...
// or in a fragment
... public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setCurrentLanguage();
View rootView = inflater.inflate(R.layout.fragment_preferences,
container, false); ...
再次感謝你的幫助 ;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.