0

i have a viewpager activity containing fragment named OneFragment.

The Onefragment contains a recyclerview,on items click a fragment called DescriptionFragment opens.

This is how i opened the DescriptionFragment from the Adapter:

 Fragment descriptionFragment = new DescriptionFragment ();
                FragmentTransaction transaction = mContext.beginTransaction();
                transaction.replace(R.id.framelayout, descriptionFragment).addToBackStack(null).commit();

Problem: When i click on backpress button the app finishes.

I want on backpress to close the DescriptionFragment and return back to the OneFragment

Mahdi H
  • 319
  • 6
  • 22

2 Answers2

2

Look at the getFragmentManager().popBackStack() methods (there are several to choose from)

http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()


To elaborate, this is my solution (placed in an Activity):

@Override
public void onBackPressed(){
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        Log.i("MainActivity", "popping backstack");
        fm.popBackStack();
    } else {
        Log.i("MainActivity", "nothing on backstack, calling super");
        super.onBackPressed();  
    }
}
Sanjog Shrestha
  • 827
  • 9
  • 16
  • Please one more question: How to handle the on resume method? Because when i am resuming the app it restarts it doesn t resume – Mahdi H Apr 15 '17 at 15:14
1

add fragment to stack while comitting a transaction like this

transaction.addToBackStack(OneFragment.getClass().getName);

and your transaction code should look somrething like this

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.replace(..............);
transaction.addToBackStack(null);
transaction.commit(); 
Muhib Pirani
  • 710
  • 1
  • 6
  • 15