Java – Why do I have to return a View in onCreateView instead of setting it directly?

Why do I have to return a View in onCreateView instead of setting it directly?… here is a solution to the problem.

Why do I have to return a View in onCreateView instead of setting it directly?

I’m a little confused about this method

public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState).

1) I’m not quite sure why fragment has to use this code to link it with a View or xml file.

2) Why can’t I call setContentView() directly in the fragment instead of through the onCreateView() method and return a View object.

3) What method or object returns this View as a parameter?

Solution

1) I am not so sure why a fragment has to used this code in order to
link it with a view or xml file.

This code returns a View that displays what you want on the layout.
Fragment has this method, but you can override it with your own layout, container, and package if needed. How do you cover it? Use what you returned in the method.

View v = inflater.inflate(R.layout.somelayout, container, false)

2) Why can’t I call setContentView() directly in a fragment instead of
going through onCreateView() method and return a view object.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crime);
    FragmentManager fm = getSupportFragmentManager();
}

Another reason is because onCreate in an activity must be protected, while onCreateView is public because fragments need to communicate with each other. IE。 You cannot use setContentView with multiple fragments because onCreate is protected.

3) What method or object is taking in this return View as a parameter?

The lifecycle of a fragment is controlled by FragmentManager.
Lifecycle of a Fragment

When you add a fragment to the stack, FragmentManager calls its View to see what needs to be displayed on the screen.

Related Problems and Solutions