user6542934
user6542934

Reputation:

FragmentManager Not Removing Dynamically added Fragments

I am trying to add/remove DialogFragments to/from my FragmentManager dynamically as a user performs different actions. The problem is that the FragmentManager is not properly removing all of them. I am calling the remove() function, so I am curious as to why these Fragments are not being removed. I have searched online, and the remove method is what people say you should use in order to remove Fragments from the FragmentManager.

Example Code below showing what I am doing:

            // originally added `LoginRestFragment` with TAG_LOGIN_REST_FRAGMENT tag to Fragment Manager
            rest = new SettingsDialogFragment();
            FragmentManager fm = getFragmentManager();
            rest.setArguments(bundle);
            Fragment fragment = fm.findFragmentByTag(TAG_LOGIN_REST_FRAGMENT);
            Log.d("frag_type", fragment.toString());
            fm.beginTransaction().remove(fragment).commit();
            fragment = fm.findFragmentByTag(TAG_LOGIN_REST_FRAGMENT);
            Log.d("is_frag_removed", fragment.toString());
            // why does this return a Fragment type ^^ shouldn't it throw null errror?
            Log.d("rest", rest.toString());
            // ^ this shows rest has been updated from LoginRestFrament to SettingsDialogFragment
            fm.beginTransaction().add(rest, TAG_LOGIN_REST_FRAGMENT).commit();
            fragment = fm.findFragmentByTag(TAG_LOGIN_REST_FRAGMENT);
            Log.d("frag_type", fragment.toString());
            // why is this not SettingsDialogFragment??

Log Statements showing what is represented. I should note that what is shown on the screen is no longer the LoginRestFragment, but the SettingsDialogFragment (as is expected), and rest is a class variable.

D/frag_type: LoginRestFragment
D/is_frag_removed: LoginRestFragment
D/rest: SettingsDialogFragment
D/frag_type: LoginRestFragment

Upvotes: 1

Views: 96

Answers (1)

user6542934
user6542934

Reputation:

Thank you DeeV! What you said is true, and it is how I found a workaround to solve this that is answered in this StackOverflow entry. You can essentially just use executePendingTransactions() on your FragmentManager to make commits dynamically.

Upvotes: 1

Related Questions