Here's why you saw the menu with the code you listed in your onClick
method:
You were creating an Intent with the constructor that takes a string for the action parameter of the Intent
's IntentFilter
. You passed "android.intent.action.MAIN"
as the argument to that constructor, which specifies that the Intent
can be satisfied by any Activity
with an IntentFilter including <action="android.intent.action.MAIN">
.
When you called startActivity
with that Intent
, you effectively told the Android OS to go find an Activity
(in any app installed on the system) that specifies the android.intent.action.MAIN
action. When there are multiple Activities that qualify (and there are in this case since every app will have a main Activity
with an IntentFilter
including the "android.intent.action.MAIN"
action), the OS presents a menu to let the user choose which app to use.
As to the question of how to get back to your main activity, as with most things, it depends on the specifics of your app. While the accepted answer probably worked in your case, I don't think it's the best solution, and it's probably encouraging you to use a non-idiomatic UI in your Android app. If your Button
's onClick()
method contains only a call to finish()
then you should most likely remove the Button
from the UI and just let the user push the hardware/software back button, which has the same functionality and is idiomatic for Android. (You'll often see back Buttons used to emulate the behavior of an iOS UINavigationController navigationBar which is discouraged in Android apps).
If your main activity launches a stack of Activities and you want to provide an easy way to get back to the main activity without repeatedly pressing the back button, then you want to call startActivity
after setting the flag Intent.FLAG_ACTIVITY_CLEAR_TOP
which will close all the Activities in the call stack which are above your main activity and bring your main activity to the top of the call stack. See below (assuming your main activity subclass is called MainActivity:
btnReturn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
)};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…