Android在SharedPreference中保存选定的货币

时间:2014-06-01 22:27:58

标签: android save currency shared preference

在我的活动中,用户选择是否显示加拿大或中国货币。我想保存这个选择,我认为最好的方法是将它保存在SharedPreferences中。我该怎么办?

 NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CANADA);
 nf.setCurrency(Currency.getInstance(Locale.getDefault()));

 NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
 nf.setCurrency(Currency.getInstance(Locale.getDefault()));

1 个答案:

答案 0 :(得分:0)

保存:

SharedPreferences sharedPrefs = getSharedPreferences("currency", MODE_PRIVATE);
sharedPrefs.edit().putString("code", nf.getCurrency().getCurrencyCode()).commit();      

然后,恢复它:

SharedPreferences sharedPrefs = context.getSharedPreferences("currency", MODE_PRIVATE);
nf.setCurrency(sharedPrefs.getString("code", defaultCurrency)); 

defaultCurrency应该是默认值。例如:

String defaultCurrency = Currency.getInstance(Locale.getDefault()).getCurrencyCode();