简体   繁体   English

怎么回到android中的主要活动?

[英]how back to the main activity in android?

I have a MainActivity "A", which have a button that launch activity "B", and activity "B" have another button that launch activity "C". 我有一个MainActivity “A”,它有一个启动活动“B”的按钮,活动“B”有另一个启动活动“C”的按钮。 In the activities B and C, both have onBackPressed() method, which appears an AlertDialog asking if the user wants to return to MainActivity . 在活动B和C中,两者都有onBackPressed()方法,它出现一个AlertDialog询问用户是否想要返回MainActivity If they press yes, the program should show MainActiviy. 如果他们按是,程序应显示MainActiviy。

The question is: in activity B, i have not problem, simply call the finish() method, and MainActivity appears, but the problem is in activity C, if i call a finish() method, the program is back to activity B. How back to MainActivity from activity C?? 问题是:在活动B中,我没有问题,只需调用finish()方法,然后出现MainActivity ,但问题出在活动C中,如果我调用finish()方法,则程序返回活动B.如何从活动C ??回到MainActivity

try this on you onBackPressed: 试试你onBackPressed:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

this clears the activity stack and opens your main activity. 这会清除活动堆栈并打开您的主要活动。 No matter which activity you are, you will always go back to the main activity and all other activities are removed from the stack. 无论您是哪种活动,您都将返回主活动,并从堆栈中删除所有其他活动。

Use the following in your manifest file for the activity B and C: 在清单文件中使用以下活动B和C:

<activity android:name=".ActivityB"
            android:parentActivityName=".MainActivity"/>
<activity android:name=".ActivityC"
            android:parentActivityName=".MainActivity"/>

您可以尝试ActivityCompat.finishAffinity并在Activity C上启动MainActivity。

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

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