问题
I'm creating an AlertDialog
. Here's the snippet of code that I'm using:
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
This works fine but I haven't been able to figure out how save the selection option somewhere so that the next time the alert dialog is opened, the previously selected option is shown. I don't need this value to persist across application restarts, only as long as the application is in the background and not entirely discarded.
Being new to Android development, I have found this pretty difficult to accomplish.
回答1:
Use the code below :
private static final String SELECTED_ITEM = "SelectedItem";
private SharedPreferences sharedPreference;
private Editor sharedPrefEditor;
private void showAlert() {
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
saveSelectedItem(item);
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private int getSelectedItem() {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(this);
}
return sharedPreference.getInt(SELECTED_ITEM, -1);
}
private void saveSelectedItem(int item) {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = sharedPreference.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, item);
sharedPrefEditor.commit();
}
For the first time, nothing will be selected. From second time onwards the item which is previously selected will be selected by default.
来源:https://stackoverflow.com/questions/12137218/persist-alertdialog-options