here我可以看到,使用目标C可以处理Singleton中的多语言。我希望它也可以用Java完成。
我想要类似的东西,当用户从微调器中选择语言时,应该将所选语言设置为当前语言。并且使用get方法在所有活动中检索当前语言。有可能吗?如果是,怎么样?
这是我到目前为止所做的事情;
My Singleton Class;
public class SharedMemory {
private String currentLanguage;
private static SharedMemory instance;
private SharedMemory() {
}
public static SharedMemory getInstance() {
if (instance == null)
instance = new SharedMemory();
return instance;
}
public String getCurrentLanguage() {
return currentLanguage;
}
public void setCurrentLanguage(String currentLanguage) {
this.currentLanguage = currentLanguage;
}
我的基础活动课程;
public class Base_Activity extends Activity {
private String currentLanguage;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
final Spinner spinner = (Spinner) menu.getItem(0).getActionView()
.findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.languages, R.layout.spinner_row);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
currentLanguage = spinner.getSelectedItem().toString();
Log.i("Seted Language", currentLanguage);
switch (arg2) {
case 0:
// do nothing
break;
case 1:
setLocale("en_US");
break;
case 2:
setLocale("fi");
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// Locale.setDefault(Locale.ENGLISH);
}
});
return super.onCreateOptionsMenu(menu);
}
public void setLocale(String currentLanguage) {
Locale myLocale = new Locale(currentLanguage);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
recreate();
SharedMemory.getInstance().setCurrentLanguage(currentLanguage);
}
}
但是在这里,语言已从我不想要的Locale更改。
答案 0 :(得分:0)
我使用SharedPreferences执行此操作:
String firstLocale = getResources().getConfiguration().locale.toString().substring(0, 2);
String currentLocale = PreferenceManager.getDefaultSharedPreferences(this).getString("locale", firstLocale);
Locale locale = new Locale((String) currentLocale);
Configuration config = new Configuration();
config.locale = locale;
Locale.setDefault(locale);
它在我的应用程序中运行良好。