java - 应用程序重新启动时保存 View 状态android

标签 java android

我目前是 android 的新手,正在开发一个笔记应用程序,所以请耐心等待。在菜单中,我实现了一个选项,用户可以根据需要更改 View (列表或网格)。

 LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View customTitleView = inflater.inflate(R.layout.dialog_menu, null);
        mListViewSelect = (LinearLayout) customTitleView.findViewById(R.id.list_select);
        mGridViewSelect = (LinearLayout) customTitleView.findViewById(R.id.grid_select);
case R.id.changeView:
                final AlertDialog alertbox = new AlertDialog.Builder(this).create();
                alertbox.setCancelable(true);
                alertbox.setView(customTitleView);
                alertbox.show();
                mListViewSelect.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mListNotes.setVisibility(View.VISIBLE);
                        mGridNotes.setVisibility(View.GONE);
                        alertbox.dismiss();
                    }
                });
        mGridViewSelect.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mListNotes.setVisibility(View.GONE);
        mGridNotes.setVisibility(View.VISIBLE);
        alertbox.dismiss();
    }
});
        }
        return super.onOptionsItemSelected(item);
    }

这非常有效。但是,我希望应用程序在用户最初选择的选定 View 中打开。例如,如果用户在 gridview 中关闭了应用程序,则应用程序应在重新启动时在 gridview 中打开。

我知道我需要通过共享偏好或其他方式持久保存数据。但我需要确切地知道我需要做什么。

最佳答案

如果您想将数据保存在共享首选项中,这里有一种方法。

首先您需要创建 SharedPreferences 和 SharedPreferences.Editor 的实例:

private SharedPreferences settings = context.getSharedPreferences("*Desired preferences file", Context.MODE_PRIVATE);

*Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).

 private SharedPreferences.Editor editor = settings.edit();

如果你需要保存一个字符串:

 editor.putString(key, val).commit()

不要忘记执行 .commit();

从 SharedPreferences 获取字符串:

String str = settings.getString(key, "");

保存整数:

只需使用:

editor.putInt(key, val).commit();

等等。

关于java - 应用程序重新启动时保存 View 状态android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45857293/

相关文章:

java - 将 AsyncTasks 的结果放在一起

java - 在java中修改函数内部参数的干净方法是什么?

java - Android虚拟设备中的 'Unfortunately Testapp has stopped'错误消息

android - 将 TURN 服务器添加到 android webRtc native

java - OpenGL ES 2.0 - 用纹理画线?

java - 如何将多个图像上传到firebase数据库并检索

java - For循环,整数值不更新

android - 在 Android Studio 中用 C++ 编写应用程序?

java - 在 Android Studio 中找不到符号类 vector

java - 嵌套viewpagers : letting the outer swipe but not the inner