Wowzer Wowzer - 1 month ago 8
Android Question

Why do I have to return a view in onCreateView instead of setting the view directly?

I am a little confuse about the method

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


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.

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

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

Answer

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 will return a view that is used to display what you want on your layout. the Fragment has this method but you override with with your own layout, container and bundle if needed. How do you override it? with what you return 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 activity must be protected whereas onCreateView is public because fragments need to communicate with each other. I.e. you can't use setContentView on 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 the FragmentManager, Lifecycle of a Fragment

When you add the fragment to the stack, its view is called by the FragmentManager to see what is required to be put on screen.