【发布时间】:2018-12-17 18:50:19
【问题描述】:
我将复选框文本和isChecked 保存到SharedPreferences 中,使用for each loop 获取复选框值,我使用HashMap 存储所有值。
我保存复选框文本和 isChecked 的代码:
HashMap<String,Object> amenityMap = new HashMap<>();
for(CheckBox checkBox : checkBoxes){
if(checkBox.isChecked()){
amenityMap.put(checkBox.getText().toString().trim(),true);
}
}
saveHashMapSharedPreferences(parentActivity, amenityMap, Amenity.AMENITY_DETAILS,Amenity.AMENITY_DETAILS);
SharedPreference 方法:
public static void saveHashMapSharedPreferences(Activity parentActivity,HashMap<String,Object> amenityMap,String spType, String key) {
SharedPreferences appSharedPrefs = parentActivity.getSharedPreferences(spType, Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(amenityMap); //tasks is an ArrayList instance variable
prefsEditor.putString(key, json);
prefsEditor.apply();
}
下图是SharedPreferences.xml中保存的checkbox值:
所以它的key是amenityDetails,checkbox的值都在那里。
如何从此 SharedPreference 中检索复选框值并将其设置回 isChecked 的复选框?
【问题讨论】:
标签: android foreach hashmap sharedpreferences