简体   繁体   English

在Android中启动其他活动时如何完成活动?

[英]How to finish Activity when starting other activity in Android?

I have problems to finish the activity before.我之前完成活动时遇到问题。 I want to start another activity and finish the current activity.我想开始另一个活动并完成当前的活动。 When I used finish it didn't exit the current activity.当我使用finish它没有退出当前活动。

How can I exit the activity before?我怎样才能退出活动?

You need to intent your current context to another activity first with startActivity .你需要intent当前的context ,以另一个活动先用startActivity After that you can finish your current activity from where you redirect.之后,您可以从重定向的位置finish当前的activity

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

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) - Clears the activity stack. intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) - 清除活动堆栈。 If you don't want to clear the activity stack.如果您不想清除活动堆栈。 PLease don't use that flag then.请不要使用那个标志。

Intent i = new Intent(this,NewLaunchingActivity.Class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Call Only, if you dont want to come back to this activity on back press, else ignore this line
    startActivity(i);
    finish();

The best - and simplest - solution might be this:最好的——也是最简单的——解决方案可能是这样的:

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

Documentation for finishAndRemoveTask() : finishAndRemoveTask()文档:

Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.当您的活动完成并且应该关闭并且任务应该作为完成任务的根活动的一部分被完全删除时调用它。

Is that what you're looking for?这就是你要找的吗?

  1. Make your activity A in manifest file: launchMode = "singleInstance"在清单文件中launchMode = "singleInstance"您的活动 A: launchMode = "singleInstance"
  2. When the user clicks new, do FirstActivity.fa.finish();当用户点击new时,做FirstActivity.fa.finish(); and call the new Intent.并调用新的 Intent。
  3. When the user clicks modify, call the new Intent or simply finish activity B.当用户点击修改时,调用新的 Intent 或简单地完成活动 B。
startActivity(new Intent(context, ListofProducts.class)
    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));

For eg: you are using two activity, if you want to switch over from Activity A to Activity B例如:您正在使用两个活动,如果您想从活动 A 切换到活动 B

Simply give like this.像这样简单地给予。

          Intent intent = new Intent(A.this, B.class);
         startActivity(intent);
         finish();

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

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