Search code examples
androidandroid-layoutandroid-fragmentsandroid-appcompatpreferencefragment

Fragment doesn't show second time it's used


I have a single Activity architecture where I'm loading a PreferenceFragmentCompat inside another ViewGroup in the MainActivity. Custom navigation exists within the MainActivity so that you can load the ViewGroup with the fragment and navigate away from it all within the same MainActivity.

The first time I navigate to the ViewGroup, the PreferenceFragmentCompat loads perfectly fine. However, when I navigate away from the ViewGroup containing the PreferenceFragmentCompat and then back again, the PreferenceFragmentCompat does not show up subsequent times. The ViewGroup does, but it's empty where the fragment should be. I can see through breakpoints/logging that the fragment is going through its lifecycle--it just isn't visible.

A new containing ViewGroup and a new PreferenceFragmentCompat object pair is created every time I navigate back to the ViewGroup, so it shouldn't be getting attached to an old ViewGroup. The navigation architecture is too complicated to post here, but here's how I'm adding the fragment in the containing ViewGroup class each time:

CustomPreferenceFragment fragment = new CustomPreferenceFragment();
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_frame_container, fragment);
ft.commit();

Does anyone have any idea why the fragment might not be showing up?


Solution

  • I found the issue. It was a lot simpler than I expected. Because a new ViewGroup was being created every time, the fragment was being added to the old ViewGroup before it could be replaced by the new one, since they both contain the R.id.fragment_frame_container view. The solution was to just not create a new ViewGroup each time if it already existed.