Persist Alertdialog Options
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.Builde
Solution 1:
Use the code below :
privatestaticfinalStringSELECTED_ITEM="SelectedItem";
private SharedPreferences sharedPreference;
private Editor sharedPrefEditor;
privatevoidshowAlert() {
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, getSelectedItem(), newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int item) {
saveSelectedItem(item);
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialogalert= builder.create();
alert.show();
}
privateintgetSelectedItem() {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(this);
}
return sharedPreference.getInt(SELECTED_ITEM, -1);
}
privatevoidsaveSelectedItem(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.
Post a Comment for "Persist Alertdialog Options"