在onCreate 中检查savedInstanceState 是否为null 是判断设备是否旋转的好方法吗?

发布于 2024-12-05 21:04:17 字数 188 浏览 0 评论 0原文

我想在 Activity 的 onCreate() 方法中执行一些操作,前提是它们是第一次构造的,而不是在设备旋转时(配置更改时)。目前我正在检查传递给 onCreate() 的 savingInstanceState 参数。如果为空,则这是 Activity 第一次启动,否则仅进行轮换。

这是一个好的、可靠的方式来讲述这一点吗?有替代方案吗?

There's stuff I'd like to do in my Activities' onCreate() method only if they're constructed the first time, not when the device was rotated (on configuration changes). Currently I'm checking the savedInstanceState parameter passed into onCreate() for this. If it's null, then it's the first time the Activity starts, else there was only a rotation.

Is this a good and reliable way to tell this? Are there alternatives to this?

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

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

发布评论

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

评论(1

烟雨扶苏 2024-12-12 21:04:17

我不知道有更好的解决方案。 Romain Guy 描述了相同的方法< /a> (检查 savingInstance 状态或您传递给 null 的其他对象)。

在新活动中,在 onCreate() 中,您所要做的就是获得您的
对象返回是调用 getLastNonConfigurationInstance()。在
Photostream,如果返回值不是,则调用此方法
null,网格加载了上一张照片的列表
活动:

private void loadPhotos() {
    final Object data = getLastNonConfigurationInstance();

    // The activity is starting for the first time, load the photos from Flickr
    if (data == null) {
        mTask = new GetPhotoListTask().execute(mCurrentPage);
    } else {
        // The activity was destroyed/created automatically, populate the grid
        // of photos with the images loaded by the previous activity
        final LoadedPhoto[] photos = (LoadedPhoto[]) data;
        for (LoadedPhoto photo : photos) {
            addPhoto(photo);
        }
    }
}

当我懒惰这样做时,我只是禁用在方向更改时重新创建活动。如如何在 Android 上禁用方向更改?中所述

I don't know of a better solution. Romain Guy describes the same approach (checking savedInstance state or other objects you pass for null).

In the new activity, in onCreate(), all you have to do to get your
object back is to call getLastNonConfigurationInstance(). In
Photostream, this method is invoked and if the returned value is not
null, the grid is loaded with the list of photos from the previous
activity:

private void loadPhotos() {
    final Object data = getLastNonConfigurationInstance();

    // The activity is starting for the first time, load the photos from Flickr
    if (data == null) {
        mTask = new GetPhotoListTask().execute(mCurrentPage);
    } else {
        // The activity was destroyed/created automatically, populate the grid
        // of photos with the images loaded by the previous activity
        final LoadedPhoto[] photos = (LoadedPhoto[]) data;
        for (LoadedPhoto photo : photos) {
            addPhoto(photo);
        }
    }
}

When I am lazy to do this, I just disable recreating the Activity on orientation change. As described at How do I disable orientation change on Android?

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