我在ActionBar中使用Dialog Builder使用SingleChoiceItems。我需要在退出应用程序后保存所选项目,以便在再次访问应用程序时恢复已保存的设置。
先决条件 - >我看到很多共享首选项和onRestoreInstance和OnSaveInstance的例子,但我很困惑。下面的代码解释了我的所作所为。
- 对话框生成器----
我在 - >中保存了所选选项的当前状态selectPosition ..然后将selectedPosition保存在全局变量isChecked中并将其设置为SelectSingleChoice参数
private void displaySortDialog() {
final CharSequence[] sort_options = {"Z-A", "A-Z", "Size"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.sort_apps));
builder.setSingleChoiceItems(sort_options, isChecked, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int selected_sort) {
Toast.makeText(getApplicationContext(), sort_options[selected_sort], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
Toast.makeText(getApplicationContext(), "Choose:"+selectedPosition, Toast.LENGTH_SHORT).show();
if(selectedPosition == 0){
Collections.shuffle(applist);
Toast.makeText(getApplicationContext(), "Shuffles the present order list", Toast.LENGTH_SHORT).show();
}
else if(selectedPosition == 1){
Collections.sort(applist, new ApplicationInfo.DisplayNameComparator(packageManager));
Toast.makeText(getApplicationContext(), "Sorts Alphabetically", Toast.LENGTH_SHORT).show();
}
else if(selectedPosition == 2){
Collections.reverse(applist);
Toast.makeText(getApplicationContext(), "Reverses the present order selected", Toast.LENGTH_SHORT).show();
}
isChecked = selectedPosition;
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
使用以下代码。当我长按home按钮的主页按钮从thr应用程序选择的设置似乎没问题,他们被选中并保存为我祝酒消息,以确保他们被选中似乎onSaveInstanceState正在工作我猜coz OnSaveInstance Toast msg显示..但是当我尝试恢复通过OnRestoreInsatanceMethod保存的设置时,它无法正常工作..退出应用程序后,设置将恢复为默认值
public void onRestoreInstanceState(Bundle savedInstanceState) {
if(savedInstanceState != null){
isChecked = savedInstanceState.getInt("SELECTED_SORT_ITEM");
Toast.makeText(getApplicationContext(), "RESTORED: "+isChecked, Toast.LENGTH_SHORT).show();
}
}
public void onSaveInstanceState(Bundle savedInstanceState) {
//outState.putInt(SELECTED_SORT_ITEM, getActionBar().getSelectedNavigationIndex());
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(SELECTED_SORT_ITEM, isChecked);
Toast.makeText(getApplicationContext(), SELECTED_SORT_ITEM+isChecked, Toast.LENGTH_SHORT).show();
}
OnSaveInstanceRestore 的Toast会在我从应用程序按回原点时显示,或者长按主页按钮再次选择应用程序。但退出应用程序后,我无法恢复所选设置..
如果你能用这些方法或其他方法帮助我,那将是值得注意的。
由于