Prevent same fragments in backstack

sumuu2211 :

I have one Activity. In this activity, multiple fragments are there. Fragments are in sequence to add, A -> B -> C -> D -> B -> C -> D

Now, when i back action perform than sequence is, D <- C <- B <- D <- C <- B <- A

But I have to perform back stack like this, D <- C <- B <- A

what is the proper way to prevent the same Fragment in the backStack?

Here is my code for adding fragments,

 if (fragment != null) {
            val transaction = fragmentManager.beginTransaction()
            if (bundle != null)
                fragment.arguments = bundle
                transaction.add(R.id.container_body, fragment)
                transaction.addToBackStack(fragTag)
                // Commit the transaction
                transaction.commit()
        }

And also for backstack perform,

 if (supportFragmentManager.backStackEntryCount > 0) {
            supportFragmentManager.popBackStackImmediate()
        }
Prakash Reddy :

When creating the fragment set a tag for it, then later you can find it through the fragment manager and replace/create new one accordingly

FragmentManager fManager = getFragmentManager();
FragmentTransaction fTransaction = fManager.beginTransaction();
Fragment fragment = fManager.findFragmentByTag("uniqueTag");

// If fragment doesn't exist yet, create one
if (fragment == null) {
     fTransaction.add(R.id.fragment_list, new ListFrag(), "uniqueTag");
 }else { // re-use the old fragment
     fTransaction.replace(R.id.fragment_list, fragment, "uniqueTag");
 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=17005&siteId=1