我有多项选择的alertdialog。我能够显示警报并能够在共享首选项中选择商店的复选框。现在我如何从共享首选项中检索并保持复选框状态。以[1,3,4]格式存储在共享pref中的值选中这些复选框。请帮忙。
final CharSequence[] ratings = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
final ArrayList selectedratings = new ArrayList();
final boolean[] ratingschecked = {false, false, false, false, false, false, false, false, false, false};
SharedPreferences sharedPreferences = getSharedPreferences("checkedrate", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
int size = sharedPreferences.getInt("size", 0);
for(int j=0;j<size;j++)
{
selectedratings.add(sharedPreferences.getString("selectedratings" + j, String.valueOf(selectedratings.get(j))));
}
for(int j=0;j<selectedratings.size();j++){
int s = (int) selectedratings.get(j);
ratingschecked[s-1]=true;
}
builder.setTitle("Select Ratings");
builder.setMultiChoiceItems(ratings, ratingschecked, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
if(!selectedratings.contains((String)String.valueOf(which+1))){
selectedratings.add(String.valueOf(which+1));
ratingschecked[which+1]=true;
}
} else if (selectedratings.contains(which + 1)) {
selectedratings.remove((String)String.valueOf(which));
ratingschecked[which]=false;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// editor.putString("checked", String.valueOf(selectedratings));
for (int i = 0; i < selectedratings.size(); i++) {
editor.putString("selectedratings" + i, String.valueOf(selectedratings.get(i)));
}
editor.putInt("size", selectedratings.size());
editor.apply();
Log.e("Shiva", String.valueOf(selectedratings));
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
builder.show();
}
答案 0 :(得分:0)
public void saveToPreferences(String key, String value) {
final SharedPreferences prefs = getSharedPreferences(PREF_FILE_CONFIG,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.apply();
}
使用上述方法保存到首选项,使用以下方法将其保存回来
public String getFromPreferences(String key) {
final SharedPreferences prefs = getSharedPreferences(PREF_FILE_CONFIG, Context.MODE_PRIVATE);
String value = prefs.getString(key, "");
if (!value.isEmpty()) {
return value;
}
return "";
}