I have a right Navigation Drawer which gets filled by an Adapter with Checkboxes. The Adapter gets the names for the checkboxes from a StringSet which is stored in Shared Preferences.
If the user checks those Checkboxes, it writes the checked boxes names into SharedPreferences after the app is closed and startet again, those checkboxes should be automatically checked. How can I achieve the latter thing?
this is my getView() Code inside my Adapter so far:
public View getView(int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = prefs.edit();
selectedStrings = prefs.getStringSet("zones", null); // get the checked Checkboxes from SP and save the Set inseide "selectedStrings"
Log.v("selectedStrings: ", selectedStrings.toString());
ViewHolder viewHolder = null;
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.nav_drawer_zones_adapter, null);
viewHolder = new ViewHolder();
viewHolder.ZoneCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox);
Log.v("CheckBox", viewHolder.ZoneCheckBox.getText().toString());
// I tried to check if the StringSet contains the name of one of the Checkboxes, if so, the box should be checken
if (selectedStrings.contains(viewHolder.ZoneCheckBox.getText().toString())){
viewHolder.ZoneCheckBox.setChecked(true);
}
if (viewHolder.ZoneCheckBox.getText().toString().equals("Zimmer")) {viewHolder.ZoneCheckBox.setChecked(true);} // A desperate try to see if it even works.
// "Zimmer" is one of the checkboxes.
convertView.setTag(viewHolder);
viewHolder.ZoneCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// ||
// \ / This works
// \/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
selectedStrings.add(buttonView.getText().toString());
editor.putStringSet("zones", selectedStrings).commit();
}else{
selectedStrings.remove(buttonView.getText().toString());
editor.putStringSet("zones", selectedStrings).commit();
}
}
});
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
Map.Entry zones = (Map.Entry) mData.get(position);
viewHolder.ZoneCheckBox.setText((CharSequence) zones.getKey());
return convertView;
}
Aucun commentaire:
Enregistrer un commentaire