Android 对话框的保存状态

标签 android dialog radio-button save state

如何在 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/

相关文章:

android - 在 Android 3.0+ 中,如何让具有自定义布局的操作按钮的样式像标准操作按钮一样

Android Room 自动迁移?

android - RecyclerView 中的确认和撤消删除

c# - 创建返回值的自定义对话框的最简单方法?

单选按钮和选中按钮的 CSS 样式在 RCP 应用程序 e4 中不起作用

android - 我如何从字节中获取字符串响应

javascript - 使用 Javascript 显示对话框

java - 在用户触摸屏幕的地方放置对话框

.net - 如何避免 Windows 窗体单选按钮容器自动分组

java - Android RadioButtons 看起来太亮