如何在android中关闭活动并返回上一个活动 [英] How to close activity and go back to previous activity in android

查看:47
本文介绍了如何在android中关闭活动并返回上一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主要活动,当我点击一个按钮时,开始一个新活动,我使用以下代码来做到这一点:

I have a main activity, that when I click on a button, starts a new activity, i used the following code to do so:

Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);

以上代码是从主要活动中运行的.

The above code was run from the main activity.

现在在由主活动调用的新活动中,我有一个后退按钮.当我点击这个后退按钮时,我希望我的新活动关闭,它必须回到原来的主要活动.

Now in my new activity which is called by the main activity, I have a back button. When I click on this back button I want my new activity to close and it must go back to the original main activity.

我试过调用 super.finish() 并且只调用 finish()(来自新活动),但这会关闭我的整个应用程序(包括我的主要活动).

I have tried calling super.finish() and just finish() (from the new activity) but this then closes my entire application (including my main activity).

如何只关闭当前处于焦点的活动,然后返回主活动?

How can I just close the activity that is currently in focus, and then return to the main activity?

已编辑

事实上,我手机的后退按钮也关闭了我的整个应用程序,让我认为我错误地启动了第二个活动?

The fact that my phone's back button also closes my entire app, leads me to think that i have started up the second activity incorrectly?

好的,我一直在寻找,

我创建了一个设置活动,它使用相同的清单代码和相同的代码来启动活动.

I created a Settings Activity that uses the same manifest code and the same code to Start the activity.

对于设置活动,当我按下后退按钮时,它返回到主活动.

For the settings Activity when I push the back button, it returns to the Main activity.

通过上面主要问题中提到的活动,它只是退出了我的整个应用程序.

With the activity mentioned above in the main question it simply exits my entire app.

所以问题似乎不在于完成活动的代码,而在于活动本身.

So the problem doesn't seem to be with the code to finish the activity but the activity itself.

推荐答案

我想你是在启动 SettingsActivity 之前调用 MainActivity 中的 finish() 方法代码>.

I think you are calling finish() method in MainActivity before starting SettingsActivity.

您所描述的场景将以以下两种方式发生:

The scenario which you have described will occur in following two ways:

要么

您已经在 AndroidManifest.xml 中为 MainActivity 设置了 android:noHistory = "true" 这会导致 MainActivity按返回键自动finish.

You have set android:noHistory = "true" for MainActivity inside AndroidManifest.xml which causes MainActivity to finish automatically on pressing the back key.

在切换到SettingsActivity"之前,您已经在 MainActivity 中调用了 finish(),这会杀死它.当您按下返回按钮时,由于堆栈中没有预设其他活动要弹出,它会返回到主屏幕.

Before switching to your 'SettingsActivity', you have called finish() in your MainActivity, which kills it. When you press back button,since no other activity is preset in stack to pop, it goes back to main screen.

这篇关于如何在android中关闭活动并返回上一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆