1

I have 4 buttons in a fragment. When I click one button 'A' a fragment is loaded. When click on button 'B' another fragment is loaded and so on. My problem is when again i clicked on the Button A new fragment is loading. I want to load the previous fragment from the backStack.

    if(rootView.findViewById(R.id.talk_main_container)!=null){
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            Bundle bundle=new Bundle();
            bundle.putString("cityid", cityId);
            if(position == 1){
                MainForumsFragment mTalkNewFragment = new MainForumsFragment(); 
                mTalkNewFragment.setArguments(bundle);
                transaction.replace(R.id.talk_main_container, mTalkNewFragment);  
            }
            if(position == 2){
                TalkNewFragment mTalkNewFragment = new TalkNewFragment();  
                mTalkNewFragment.setArguments(bundle);
                transaction.replace(R.id.talk_main_container, mTalkNewFragment);  
            }
            if(position == 3){
                TalkNewFragment mTalkNewFragment = new TalkNewFragment();  
                mTalkNewFragment.setArguments(bundle);
                transaction.replace(R.id.talk_main_container, mTalkNewFragment);  
            }
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.addToBackStack(null);
            transaction.commit();  
        }

So how can I achieve that?

3 Answers3

1

Don't add any fragment to backstack

Remove transaction.addToBackStack(null);

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
Chetan Gaikwad
  • 1,268
  • 1
  • 13
  • 26
0

You should use

FragmentTransaction.replace(int containerId, Fragment fragment, String tag)

Then you can get the fragment back:

getFragmentManager.findFragmentByTag(String tag)
Dara
  • 107
  • 1
  • 7
0

Add specific string tag when you add Fragments to backstack, instead of addBackStack(null).

You can pop fragment from the backstack using popBackStack(tag, 0) or popBackstackImmediate(). This will pop all fragments until it finds the fragment with specified tag.

Make sure you are careful with order of lifecycle events when this operation is performed

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148