本文介绍了打开信息活动而不关闭主活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个具有两个活动的简单android应用程序.一个MainActivity和一个InfoActivity.我在ActionBar上有一个按钮,然后单击要打开InfoActivity的按钮.在我的InfoActivity中,有一个后退按钮,该按钮会删除我的InfoActivity并再次打开MainActivity.我可以在不关闭MainActivity的情况下打开InfoActivity吗?

I'm making a simple android application with two activities. one MainActivity and one InfoActivity. I have a button on my ActionBar and on click I want to open my InfoActivity. In my InfoActivity I have a back button, that removes my InfoActivity and open my MainActivity again. Can I open the InfoActivity without closing my MainActivity?

我正在从Internet的主要活动中解析JSON,并且我不希望它在关闭InfoActivity时再次加载所有内容.

I'm parsing JSON from internet my Main Activity, and I don't want it to load everything again when I close the InfoActivity.

用于打开InfoActivity的代码:

Code for opening InfoActivity:

  private View.OnClickListener onInfoBtnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MainActivity.this, InfoActivity.class);
            startActivity(intent);
        }
    };

在InfoActivity类中关闭InfoActivity的代码:

Code for closing InfoActivity in InfoActivity class:

private View.OnClickListener onBackBtnClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(InfoActivity.this, MainActivity.class);
        startActivity(intent);
    }
};

推荐答案

我可以在不关闭MainActivity的情况下打开InfoActivity吗?

否,因为InfoActivity处于状态stopped,所以它将被调用到前台,而MainActivity将在后台被调用.问题是,如果您像这样在InfoActivity中触发Intent,则除了旧实例之外,还会有MainActivity的新实例.

No, the InfoActivity will be called to the foreground and MainActivity in the background, because it will be in the state stopped. The problem is if you fire the Intent in your InfoActivity like this, there will be a new instance of the MainActivity besides the old instance.

在您的Intent调用中添加一个标志,以防止MainActivity的新实例.然后将从堆栈中调用它.

Add a flag to your Intent call to prevent a new instance of the MainActivity. Then it will be called from the stack.

private View.OnClickListener onBackBtnClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(InfoActivity.this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
};

或简单调用finish(),例如hamad和Aerrow建议.然后,将销毁InfoActivity并从堆栈中调用MainActivity.

Or simple call finish(), like hamad and Aerrow suggested. Then the InfoActivity will be destroyed and the MainActivity will be called from the stack.

这篇关于打开信息活动而不关闭主活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 22:11