Fragment lifecycle events in LifeCycleAware Fragment

user4260260 picture user4260260 · Nov 3, 2017 · Viewed 8.1k times · Source

I have a lifecycle aware fragment and a LifecycleObserver class

        public class MyFragment extends Fragment {
            @Override
            public void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                new MyObserver(this);

            }

            @Nullable
            @Override
            public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
                return inflater.inflate(R.layout.activity_main, container, false);
            }
        }

Following is my Observer class where it logs all the fragment events propery

        public class MyObserver implements LifecycleObserver {
            private static final String TAG = "MyObserver";
            public MyObserver(LifecycleOwner lifecycleOwner) {
                lifecycleOwner.getLifecycle().addObserver(this);
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
            public void onCreate(){
                Log.d(TAG, "onCreate: ");
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
            public void onPause(){
                Log.d(TAG, "onPause: ");
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            public void onDestroy(){
                Log.d(TAG, "onDestroy: ");
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_START)
            public void onStart(){
                Log.d(TAG, "onStart: ");
            }

        }

I want to listen to fragment specific lifecycle events like onDestroyView and onActivityCreated but these events are not there in

Lifecycle.Event. It contains only activity events. How can I listen for fragment events in my observer

Answer

Basim Alamuddin picture Basim Alamuddin · Feb 8, 2019

You can observe the fragment's viewLifecycleOwner lifecycle.

viewLifecycleOwner.lifecycle.addObserver(yourObserverHere)

Then the fragment's onDestroyView lifecyle method is tied to the @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) annotated method.

Note that the fragment's viewLifecycleOwner is only available between onCreateView and onDestroyView lifecycle methods.