[英]Persist AlertDialog options
我正在创建一个AlertDialog
。 这是我正在使用的代码片段:
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();
}
第一次,什么也不会选择。 从第二次起,默认情况下将选择先前选择的项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.