3

I wonder what is container parameter in onCreateView(), cause when i inflate view to that container it make me wonder what viewGroup is this,is it a viewGroup from the activity that we will add a fragment to ? if it is true then why we need to attach it in inflate method cause i think we will add this fragment to the viewgroup of activity in activity's xml anyway.

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_top,container,true);
    return view;
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Tú Anh Dư
  • 135
  • 1
  • 10

3 Answers3

1

The inflate() method takes three arguments:

  • The resource ID of the layout you want to inflate.

  • The ViewGroup to be the parent of the inflated layout. Passing the container is important in order for the system to apply layout parameters to the root view of the inflated layout, specified by the parent view in which it's going.

  • A boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during inflation.

For more refer here

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Rissmon Suresh
  • 13,173
  • 5
  • 29
  • 38
0

To be more specific, I think the container is the FragmentContainerView in this example. Basically it's the resource id which you add your fragment to. For example, if we do

fragmentTransaction.add(R.id.container_view, fragment).commitNow();

Then the container is the ViewGroup identified by R.id.container_view.

Changda Li
  • 123
  • 1
  • 8
0

Quoting the docs

container ViewGroup: If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view. This value may be null.

Yousef Gamal
  • 1,026
  • 2
  • 17
  • 32