【问题标题】:Pressing back button calls onCreate (Android)按返回按钮调用 onCreate (Android)
【发布时间】:2014-08-05 06:04:25
【问题描述】:

Activity A 启动 Activity B。在 Activity B 中,我有这个方法:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. Use NavUtils to allow users
        // to navigate up one level in the application structure. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        NavUtils.navigateUpTo(this, new Intent(this,
                ArticleListActivity.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
}

当我按下主页按钮时,它会将我带到应有的活动 A。但是,再次调用 onCreate。我不希望这种行为。

我猜是因为这个实现对导航堆栈中的前一个项目使用了新的 Intent。这只是我在创建双窗格项目时从 Eclipse 获得的代码。我环顾四周,发现堆栈溢出,虽然似乎使用 Intent 返回会导致这种行为,但我不明白为什么 Google 会在默认模板中提供这个。

我应该如何以不同的方式进行此调用,以便在返回 Activity A 时不会再次调用 onCreate?

【问题讨论】:

标签: android android-intent android-activity


【解决方案1】:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
       finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

只要完成当前的活动,它就会带你进入以前的活动 如果您之前的活动是活动 A,那么只需使用 finish();方法而不是创建意图对象

【讨论】:

  • 谢谢,伙计。作为一名 iOS 开发人员,我一直在寻找返回主表的简单无缝​​导航。这做的很棒!
【解决方案2】:

正如@Rajesh 所指出的,您需要调用 onBackPressed()

您的代码检测到主页按钮按下并创建一个新的 ArticleListActivity 类。但是,您不想创建一个新类,您只想返回到您已经创建的类/活动。所以请改用 onBackPressed()

【讨论】:

    【解决方案3】:

    你可以尝试在manifest中设置启动模式,因为父activity可以从栈中弹出。

    android:launchMode="singleTop"
    

    【讨论】:

      【解决方案4】:

      这样就不会再调用onCreate()了。

      @Override
      public void onBackPressed() {
          super.onBackPressed();
          finish();
      }
      

      【讨论】:

        猜你喜欢
        • 2014-09-27
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多