简体   繁体   English

在Android中来回切换活动

[英]Switching activities back and forth in Android

I'm starting on Android and got a beginner question on switching between multiple activities. 我开始使用Android并且在多个活动之间切换时遇到了一个初学者问题。

I understand i can go between two activities by invoking an intent and then returning with setResult(). 我理解我可以通过调用一个intent然后使用setResult()返回两个活动。 What I want to know is how to jump between multiple activities. 我想知道的是如何在多个活动之间跳转。 Specifically I want to learn about the process life-cycle. 具体来说,我想了解过程生命周期。 I understand how every activity is started ar onCreated(), but I'm not sure how to implement onResume() or onRestart() when I want to come back. 我理解每个活动是如何在onCreated()中启动的,但是当我想回来时,我不确定如何实现onResume()或onRestart()。

So basically I have 3 activities: Activity1, Activity2 and Anctivity3. 所以基本上我有3个活动:Activity1,Activity2和Anctivity3。

I start with Activity1 and then invoke Activity2 with an Intent, and Activity2 invokes Activity3. 我从Activity1开始,然后用Intent调用Activity2,Activity2调用Activity3。 Using buttons. 使用按钮。 Now I want to come back to Activity1 from Activity3. 现在我想从Activity3回到Activity1。 I do the same thing here too. 我也在这里做同样的事情。 Make an Intent and call startActivity(Activity1_Intent). 创建一个Intent并调用startActivity(Activity1_Intent)。 But it gives a runtime error. 但它给出了运行时错误。

I think I need to implement OnResume() or onRestart(), but I'm not sure how to do this. 我想我需要实现OnResume()或onRestart(),但我不知道该怎么做。 In onCreate() I make a gridView, so when I come back, do I need to make that gridView again? 在onCreate()中我创建了一个gridView,所以当我回来时,我是否需要再次创建该gridView?

If anybody could give a small explanation of refer to a tutorial it would be great. 如果有人可以给出一个小的解释,参考一个教程,这将是伟大的。 Thank you very much. 非常感谢你。

In your manifest file set android:launchMode="singleTop" to your Activity1. 在您的清单文件中将android:launchMode =“singleTop”设置为您的Activity1。

Then to call your Activity1 use: 然后调用Activity1使用:

Intent intent = new Intent(this, Activity1 .class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

FLAG_ACTIVITY_CLEAR_TOP: If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent. FLAG_ACTIVITY_CLEAR_TOP:如果已设置,并且正在启动的活动已在当前任务中运行,则不会启动该活动的新实例,而是将关闭其上的所有其他活动,并将此Intent传递给(现在在上面)旧活动作为一个新的意图。

FLAG_ACTIVITY_NEW_TASK: If set, this activity will become the start of a new task on this history stack. FLAG_ACTIVITY_NEW_TASK:如果设置,此活动将成为此历史堆栈上新任务的开始。

http://developer.android.com/reference/android/content/Intent.html http://developer.android.com/reference/android/content/Intent.html

从Android 4.0开始,您只需在Manifest文件中设置android:launchMode =“singleTask” ,然后就不需要编写Java了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM