I have 2 Activity(s). Inside 1st Activity there is initially one Fragment
MainActivity.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
if(savedInstanceState == null) {
getFragmentManager().beginTransaction().replace(R.id.fragmentContainer, MainFragment.newInstance().commit();
}
}
}
then clicking on a button replaces it with another Fragment.
@Override
public void onClick(View arg0) {
DetailFragment detail = (DetailFragment)getFragmentManager().findFragmentById(R.id.detail);
getFragmentManager().beginTransaction().replace(R.id.detail, detail, "detail").commit();
}
On 2nd Fragment there is another button, clicking on it opens a New Activity.
Intent popUp = new Intent(MainActivity.this, PopUp.class);
popUp.putExtra("CarID", carID);
startActivity(popUp);
From PopUp Activity, pressing device back will go back to MainActivity. Now the challenge is for the Application's business logic I need to update the ActionBar's title of previous MainActivity when user goes back.
For this I'm listening for onResume() on both MainFragment and DetailFragment. Also when user goes back from DetailFragment to MainFragment I update the ActionBar title with different text.
So I need to know when exactly user goes back from:
1) PopUp Activity > Detail Fragment
2) Detail Fragment > Main Fragment
Currently onResume() is fired on both MainFragment and DetailFragment when PopUpActivity is closed. On MainFragment I can't exactly find out whether onResume() is called for 1st or 2nd case.
What is the best practice to fire onResume() on DetailFragment only when user goes back from PopUpActivity > DetailFragment. In other words, how do I detect from DetailFragment that PopUpActivity is closed without firing onResume() on MainFragment.
I wouldn't mess with
onResume()for something like this.I would suggest doing the following:
Stack<String>for titles.FragmentManager.OnBackStackChangedListenerin yourMainActivity.onBackStackChanged()implementation, check if the back stack has been pushed or popped usingFragmentManager.getBackStackEntryCount().PopupActivitywithstartActivityForResult()instead ofstartActivity().onActivityResult()in yourMainActivityso that whenPopupActivityreturns, you set the title bar with the title at the top of stack.onSaveInstanceState()in yourMainActivityand restore it inonCreate().That might seem like a lot of work just for maintaining titles, but you will drive yourself crazy trying to do this with
onResume.