androidandroid-fragmentsfragmentfragment-lifecycle

In an Android Fragment, why is a call to superclass not made on `onCreateView`?


Reading through "Head First Android Development", I noticed this issue on page 367.

The code is an implementation of a Fragment, and a couple of life cycle methods are overridden, namely onCreateView and onStart.

onStart() looks like this:

@Override
public void onStart() {
  super.onStart();
  ...
}

whereas onCreateView looks like this:

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

Notice that onStart includes a call to the overridden method, via super.onStart(), whereas onCreateView does not call its overridden method.

Why does onStart make the super call, while onCreateView does not?

Also on this page, there is bold text, reading:

You should always call up to the superclass when you implement any fragment lifecycle methods.

If this is the case, then why does the onCreateView method not call up to the superclass?

The page in question is shown below.

The page in question; Head First Android page 367


Solution

  • That comment is correct. You should always call the superclass lifecycle method. because they do stuff. onCreateView of Fragment is as follow:

    onCreateView

    That mContentLayoutId is a layout Res id which you can in fragment's constructor: Fragment's secondary constructor

    What it does is to inflate the resource layout mContentLayoutId which you can pass to fragment's Constructor and return the result, and if not set return null.

    because you want to inflate your layout, you do not need this. You can call it though, but it has no effect (unless you pass a layout resource to fragment constructor and want to do something with the return view, which I do not recommend because onViewCreated exists.