Search code examples
javaandroidfragmentrefreshrelease

How to refresh Android Fragment v1.3.0 in Java


As of the new Fragment version 1.3.0, refreshing a fragment within itself does not seem to work as it had in version 1.2.5.

The code that works for my project on version 1.2.5:

FragmentTransaction ft = getFragmentManager().beginTransaction();
if (Build.VERSION.SDK_INT >= 26) {
   ft.setReorderingAllowed(false);
}
ft.detach(this).attach(this).commit();

But using this in v1.3.0 fails to refresh the Fragment.

Does anyone have a solution to this issue? I couldn't find documentation in the release notes that detailed any changes that would be the issue. Thanks!


Solution

  • As per this issue:

    This is working as intended with the new state manager as mentioned in the Fragment 1.3.0-beta01 release notes as a requirement to fix an issue where exiting fragment views were not consistently removed before adding the entering one (aosp/1427376) which actually fixes a number of edge cases which can cause crashes.

    You can change your code to do this recreation as two separate transactions:

    fun Fragment.recreateView() {
        parentFragmentManager
            .beginTransaction()
            .detach(this)
            .commitNow()
        parentFragmentManager
            .beginTransaction()
            .attach(this)
            .commitNow()
    }
    

    It goes on to say:

    You might want to star b/173472486 for tracking a Lint warning to offer a quick fix exactly this pattern and b/165840276 for adding a first class API to fragments to recreate its view without needing detach()/attach().