如何在 android 中保存对话框的状态?我有以下带有单选按钮的对话框,但不知道如何保存对话框的状态。感谢您的帮助
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();
最佳答案
您应该在用户单击时存储所选项目的位置。然后在显示列表时查找以前存储的索引。如果没有先前存储的值,则返回 -1。
我有一个应用程序首选项助手类 ...
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();
}
}
然后,在我的代码中我创建了一个字段变量...
protected AppPreferences appPrefs;
并在 Activity onCreate() 中实例化它的一个实例 ...
appPrefs = new AppPreferences(getApplicationContext());
然后将您的“-1”替换为...
builder.setSingleChoiceItems(items, appPrefs.getItemIndex(), new DialogInterface.OnClickListener() {
并在您的 onClick() 中确保您...
appPrefs.saveItemIndex(item);
关于Android 对话框的保存状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5972823/