我正在创建一个AlertDialog
。这是我正在使用的代码 fragment :
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();
这工作正常,但我无法弄清楚如何将选择选项保存在某处,以便下次打开警报对话框时显示先前选择的选项。我不需要在应用程序重新启动时保留该值,只要应用程序位于后台且未完全丢弃即可。
作为 Android 开发新手,我发现这很难完成。
最佳答案
使用下面的代码:
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();
}
第一次,不会选择任何内容。从第二次开始,将默认选择先前选择的项目。
关于java - 保留警报对话框选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12137218/