退出时如何保存 Activity 的状态?安卓

发布于 2024-08-22 13:44:07 字数 242 浏览 2 评论 0原文

我有一个基本的应用程序,其中包含文本输入、旋转器输入和第二个旋转器输入,其数组取决于“选项”菜单中更改的设置。

目前,当我在应用程序中按 Home 或按 Return 时,我要么返回桌面,要么循环返回最近输入的旧输入。

如何防止我的应用程序打开自身的多个实例,以便在任何给定时间只有一个实例运行,然后如何保存输入到输入中的数据以及在选项菜单中选择的设置?

我对 Java 有点陌生,所以如果这是一个简单的问题,我深表歉意。

I have a basic app with text inputs, a spinner input, and a second spinner input whose array depends on a setting changed in the Options menu.

Currently, when I press Home or press Return while in my app, I either return to the desktop or cycle back through old inputs i put in recently.

How can I prevent my app from opening multiple instances of itself so that there is only one instance running at any given time, and then how can I save the data entered into inputs, and the settings chosen in my option menu?

I'm a bit new to Java, so I apologize if this is a simple problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡笑忘祈一世凡恋 2024-08-29 13:44:07

在您的活动中覆盖 onSaveInstanceState 和 onRestoreInstanceState。这些方法将允许您将数据保存到 Bundle 您还可以保存数据到首选项。在我的所有应用程序中,我都重写 onSaveInstanceState 和 onRestoreInstanceState 以将值保存和加载到 Bundle。我还将数据保存到 onPause 中的首选项并在 onResume 中加载首选项。另外,在 onCreate(Bundle savingInstanceState) 中,我做了这样的检查

    if(savedInstanceState != null)
    {
        m_mainView.restoreInstanceState(savedInstanceState);
    }
    else
    {
        m_mainView.loadGameFromDatabase(getPreferences(MODE_PRIVATE));
    }

这些做法一直对我有用。

In your acticity override onSaveInstanceState and onRestoreInstanceState. These methods will allow you to save data into a Bundle You can also save data to Preferences. In all of my applications I override both onSaveInstanceState and onRestoreInstanceState to save and load values to a Bundle. I also save data to preferences in onPause and load preferences in onResume. Also in onCreate(Bundle savedInstanceState) I do a check like this

    if(savedInstanceState != null)
    {
        m_mainView.restoreInstanceState(savedInstanceState);
    }
    else
    {
        m_mainView.loadGameFromDatabase(getPreferences(MODE_PRIVATE));
    }

These practices have always worked for me.

我做我的改变 2024-08-29 13:44:07

您必须在 Activity 上使用 onPause 重写方法并将数据保留在某处(可能是共享首选项)。
然后onResume您必须从持久性存储中读回它们并填充您的控件。

当您想要处理后退或主页按钮按下时,onSaveInstanceStaterestoreInstanceState 不是您的朋友。

You will have to use onPause overridden method on your activity and persist your data somewhere (shared preferences probably).
Then onResume you have to read them back from persistance storage and populate your controls.

onSaveInstanceState and restoreInstanceState is not your friend when you want to handle back or home button presses.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文