[Android development Note] returns the correct opening method of the Upper-layer Activity, androidactivity
Technology support http://stackoverflow.com/questions/12276027/how-can-i-return-to-a-parent-activity-correctly
First, we can see someone writing this on the Internet:
1 @Override 2 public boolean onOptionsItemSelected(MenuItem item) { 3 switch (item.getItemId()) { 4 case android.R.id.home: 5 this.getActivity().finish(); 6 return true; 7 default: 8 return super.onOptionsItemSelected(item); 9 }10 }
In this way, it seems feasible to directly write Finish?
NONONO. This method is only applicable to scenarios where you are sure to keep the parent Activity alive before closing the child Activity.
In a more complex situation (for example, a sub-Activity is started from the push.
So next, I will show you the correct posture of opening the previous Activity correctly.
Step. 1 first associate the parent-child relationship in Manifest
Use "android. support. PARENT_ACTIVITY" to associate:
1 <activity android:name=".ChildActivity"2 android:label="@string/app_name" >3 <meta-data android:name="android.support.PARENT_ACTIVITY"4 android:value=".ParentActivity" />5 </activity>
Step. 2 enable the up navigation button in the Child Activity
@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // This sentence must be written. if this sentence is left blank, onOptionsItemSelected setHasOptionsMenu (true) is not called. // enable the up navigation button if (NavUtils. getParentActivityName (getActivity ())! = Null) {getActivity (). getActionBar (). setDisplayHomeAsUpEnabled (true );}}
Here, if is used to determine whether a child Activity contains a parent Activity. if you do not do the first step, you have to kneel down.
Step. 3OnOptionsItemSelectedStart parent Activity
1 @ Override 2 public boolean onOptionsItemSelected (MenuItem item) {3 switch (item. getItemId () {4 case android. r. id. home: 5 // click the return button to return the previous Activity 6 if (NavUtils. getParentActivityName (getActivity ())! = Null) {7 // start parent Activity 8 NavUtils. navigateUpFromSameTask (getActivity (); 9} 10 return true; 11 12 default: 13 return super. onOptionsItemSelected (item); 14} 15}
In this step, we can happily start the parent Activity ~
But you will find, how does the parent Activity start a new instance instead of an existing instance?
This does not meet our needs, so the key is the next step.
Step. 4 set launchMode
Because Android uses the new method to start an Activity by default, even if an instance exists, it still requires new, new, new
Therefore, we need to make a modification and add one to the parent avti.pdf attribute of Manifest:
android:launchMode="singleTop"
In this case, everything is okay. (probably) the correct method of opening ~