How do you save the state of a dialog in android? I have the following dialog with radio buttons but can't figure out how to save the state of the dialog. Thanks for any help
final CharSequence[] items = {"Item 1", "Item 2", "Item 3"};
AlertDialog.Builder builder = new AlertDialog.Builder(Tweaks.this);
builder.setTitle("Pick an item");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
}).show();
You should store the position of the selected item when the user clicks. Then you look for a previously stored index when you display the list. If there is no previously stored value you return -1.
I have an app Preferences helper class ...
public class AppPreferences {
private static final String APP_SHARED_PREFS = "myApp_preferences"; // Name of the file -.xml
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPreferences(Context context)
{
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public int getItemIndex() {
return appSharedPrefs.getInt("itemIndex", -1);
}
public void saveItemIndex(int i) {
prefsEditor.putInt("itemIndex", i);
prefsEditor.commit();
}
}
Then, in my code I create a field variable ...
protected AppPreferences appPrefs;
And instantiate an instance of it inside the Activity onCreate() ...
appPrefs = new AppPreferences(getApplicationContext());
Then replace your "-1" with ...
builder.setSingleChoiceItems(items, appPrefs.getItemIndex(), new DialogInterface.OnClickListener() {
And in your onClick() make sure you ...
appPrefs.saveItemIndex(item);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With