如何在Android中切换Activity而不终止它们?

huangapple 未分类评论42阅读模式
英文:

How to switch Activities without killing them in Android?

问题

我有这个Activity1(餐厅),可以切换到Activity2(家)

                    Intent intent = new Intent(RestaurantActivity.this, HomeActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish(); // 切换到另一个Activity后调用一次

我的另一个Activity(家)有一个布尔值来检查我之前是否在家里过

public static boolean visitedHomeAlready = true;

if(!visitedHomeAlready) {
                        Intent intent = new Intent(HomeActivity.this, RestaurantActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish(); //
}

我的想法是:如果我之前没有访问过家并切换到餐厅Activity,我希望“记住”家里的数据,以便在回家后继续我的游戏,但它总是从家里重新开始...
我不确定我需要设置哪些标志,或者从哪个地方恢复状态,确切地说,我在切换Activity的地方。

英文:

I have this Activity1(Restaurant) which switch to Acticity2(Home)

                    Intent intent = new Intent(RestaurantActivity.this, HomeActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish(); // Call once you redirect to another activity

My other Activity (Home) has a boolean to check if I have been at Home before

public static boolean visitedHomeAlready = true;

if(!visitedHomeAlready) {
                        Intent intent = new Intent(HomeActivity.this, RestaurantActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish(); //
}

My idea is: If I have not visited the home before and switch to Restaurant Activity, I want to "remember" the data in the Home Activity to continue my game after come back home but it always start from the beginning from my home...
I am not sure which flags I have to set or which method to resume that state from where exactly where I switch the activity.

答案1

得分: 0

正如Amin在上面评论的那样,finish(); 表示第一个活动已经完成了它的工作,应用程序将会结束它,如果你将它移除,第二个活动将会启动,但是第一个活动仍然会保留在原地,你可以通过点击手机或虚拟设备上的返回按钮回到它。

英文:

As Amin commented above,the finish(); means that the first activity has finished its job and the app will end it,if you removed it the second activity will start,but the first activity will still be in its place and you can go back to it just by clicking the back button on your phone or virtual device.

huangapple
  • 本文由 发表于 2020年4月5日 00:53:41
  • 转载请务必保留本文链接:https://java.coder-hub.com/61031537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定