如何正确返回父活动

如何正确返回父活动

本文介绍了如何正确返回父活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 android 应用程序中有 2 个活动(A 和 B),我使用一个意图从活动 A 到活动 B.启用了 parent_activity:

I have 2 activities (A and B) in my android application and I use an intent to get from activity A to activity B. The use of parent_activity is enabled:

 <activity
        android:name=".B"
        android:label="B" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.app_name.A" />
  </activity>

我还使用了一个提供 UP 按钮的主题.

I also use a theme which provides an UP-button.

所以在我调用活动 BI 之后,可以使用向上按钮返回活动 A.问题是应用程序似乎再次调用了活动 A 的 onCreate() 函数,然后这不是我需要的行为.我需要活动 A 看起来和我调用活动 B 之前的样子一样.

So after I called activity B I can use the UP-button to get back to the activity A. The problem is that the application seems to call the onCreate()-function of activity A again and this is not the behaviour I need. I need activity A to look the same way like it looked before I called activity B.

有没有办法做到这一点?

Is there a way to achieve this?

我没有编写任何代码来从活动 A 启动活动 B.我认为它是由 Eclipse 自动生成的.

I didn't write any code to start activity B from activity A. I think it is auto-generated by Eclipse.

B 类看起来像:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_b, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

推荐答案

您在 Android 清单中使用标准 launchMode 声明了活动 A.根据文档,这意味着以下内容:

You declared activity A with the standard launchMode in the Android manifest. According to the documentation, that means the following:

系统总是在目标中创建活动的新实例任务并将意图路由到它.

因此,即使正确处理了任务堆栈,系统也被迫重新创建活动 A(即调用 onCreate).

Therefore, the system is forced to recreate activity A (i.e. calling onCreate) even if the task stack is handled correctly.

要解决此问题,您需要更改清单,将以下属性添加到 A 活动声明中:

To fix this problem you need to change the manifest, adding the following attribute to the A activity declaration:

android:launchMode="singleTop"

注意:调用 finish()(如之前的解决方案所建议的那样)在您完全确定时有效> 您要终止的活动 B 实例位于活动 A 的实例之上.在更复杂的工作流中(例如,从通知启动活动 B),情况可能并非如此,您必须从 B 正确启动活动 A.

Note: calling finish() (as suggested as solution before) works only when you are completely sure that the activity B instance you are terminating lives on top of an instance of activity A. In more complex workflows (for instance, launching activity B from a notification) this might not be the case and you have to correctly launch activity A from B.

这篇关于如何正确返回父活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:10