Search code examples
androidandroid-fragmentsfragmentfragment-lifecycle

Refreshing fragment doesn't call onCreate(). It's normal?


I need to recreate a fragment when user press a toggle. I'm using this function:

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

It works fine, but when calling it, onCreate isn't called, this is the sequence of methods called after recreate:

onCreateView()
onViewCreated()
onResume()

And this this is the sequence of methods called when creating it for the first time:

onCreate()
onCreateView()
onViewCreated()
onResume()

Appearently, onCreate is never called again when refreshing the fragment with that function. This will be as is for ever? Or in some circumstances can change? I'm asking it because it's perfect for me that onCreate only gets called the first time, because then I can put there code that I want to execute only one item and not when refreshing. But I need to know if it's safe or onCreate can be called when refreshing.


Solution

  • onCreate() will only be called when your fragment is being, well, created. Detaching and reattaching don't create new fragments, but onCreate() will also be called if your activity is destroyed and recreated (e.g., on a configuration change like rotation or if your app's process is killed).