Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android fragment addToBackStack(null) :how to add the same fragment to stack just one time?

when fragment use addToBackStack(null) method and click a method many times in an activity, the fragment page will save to back stack everytime, when I press back key, it will restore the same page, how to add the same fragment to stack just one time?

    mSettingBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            SettingFragment settingFragment = new SettingFragment();

            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.replace(R.id.left_framelayout, settingFragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });
like image 760
Lijun Lou Avatar asked Jan 25 '13 08:01

Lijun Lou


People also ask

How can I maintain fragment state when added to the back stack?

Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.

What does addToBackStack null do?

Use . addToBackStack(null) : If you don't want later pop more than one back stack, but still want to pop one at a time.

How can fragments be reused?

replace(): Replace an existing fragment that was added to a container. So this removes the Fragment from the stack. Use FragmentTransaction. addToBackStack() to add the Fragment on top of another(s) (the stack).


1 Answers

When adding your Fragment to the backstack you should also pass a TAG to be able to identify that Fragment:

 .addToBackStack(SettingsFragment.TAG);

Prior to adding the Fragment you will be able to check if this Fragment is allready in the backstack using :

 getFragmentMangager().findFragmentByTag(SettingsFragment.TAG);

This will return null if the Fragment is not allready added.

like image 56
Ovidiu Latcu Avatar answered Oct 24 '22 01:10

Ovidiu Latcu