Resuming a previous fragment onBackPressed()?

I have a HomeFragment that has a button, which when clicked calls the following:

Fragment frag = new CustFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.home_container, frag).commit();

Then in my FragmentActivity which is the fragments mentioned above, I have:

@Override
public void onBackPressed() {

    getFragmentManager().popBackStack();
    super.onBackPressed();

}

That's what I've tried, but if I'm on the frag fragment and I press the back button, it doesn't go back to the last fragment (the HomeFragment). Instead, it attempts to go back to the last Activity, but since there is none (i.e. the previous activity had finish() invoked on it), it just goes to the Android Home Screen.

What am I doing wrong?

PS: If I'm being unclear, just comment below and i'll try to clarify.

Answers


Change

@Override
public void onBackPressed() 
{
   getFragmentManager().popBackStack();
   super.onBackPressed();
}

to

@Override
public void onBackPressed() 
{
  if(getFragmentManager().getBackStackEntryCount() > 0)
    getFragmentManager().popBackStack();
  else
   super.onBackPressed();
}

and

fragmentManager.beginTransaction().replace(R.id.home_container, frag).commit();

to

fragmentManager.beginTransaction().replace(R.id.home_container, frag).addToBackStack(null).commit();

Add your fragment to back stack using addToBackStack(null) like..

fragmentManager.beginTransaction().replace(R.id.home_container, frag).addToBackStack(null).commit();

You can use:

fragmentTransaction.addToBackStack(null);

and no need to take care of onBackPressed().

BTW in your onBackPressed() super.onBackPressed() means you are actually changing nothing.

It should have been something like:

if(currentFragmentIsCustFragment){
   getFragmentManager().popBackStack();
}else{
   super.onBackPressed();
}

beginTransaction creates a new FragmentTransaction. It has a method addToBackstack. If you call it before you commit your transaction you can remove your overridden onBackPressed completely. Reference


Need Your Help

Mass verify svn repositories

svn corruption verify svnadmin

Hi I'm wondering if there is a tool (can be commercial) to mass verify svn repositories. I know about using svnadmin but there are about 100 repositories and it's tedious to check whether if there's

peculiar error on ntpath.py

python windows-7 path subprocess

I am trying to write a wrapper like thing on vlc player on windows 7 so that it can load next and previous files in folder with a keystroke. What I do in it is, I take a filepath as argument make an

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.