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

788 Views Asked by At

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

2

There are 2 best solutions below

0
mohsen sameti On BEST ANSWER

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.

2
dominicoder On

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

The short answer is your book is probably old.

If you check the source code, you see that onCreateView only does something if you provide a layout resource ID. It's expected that you will provide a view yourself so calling the super class serves no purpose if you're overriding the method. Moreover, onCreateView used to not even do that much, it would just return null, so calling it served no purpose. That's probably how it worked when your book was written.

By comparison, you can see that onStart not only has logic, but actively checks if you've called it (mCalled = true) and throws an exception if you didn't call it.

So for some methods it's optional to call through to super and won't have any effect, while others it's basically required (or you get an Exception).