0

When I want to create a simple fragment, usually use following code:

public class TestFragment extends Fragment {
  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_latout, container, false);
  }
}

My questions are: What exactly is container parameter? where it is defined? Can we see this ViewGroup(container) in XML/Layout Designer? In this method(onCreateView), what is this ViewGroup(container) id? In R.id.x, to access this ViewGroup(container) What should we replace x with? Thanks.

Mohammad
  • 42
  • 7

1 Answers1

0

You don't call that method, the system does, as part of the fragment lifecycle.

When a fragment is added to a layout, onCreateView will eventually get called, and container is the view that holds the fragment. That lets you do things like access the parent's layout parameters, the style/theme applied to it, etc. That's why you pass container when you call inflate, so it can apply any necessary attributes while inflating the fragment's layout.

Basically don't worry about it, and pass the parent/container when you inflate a layout. 99% of the time, that's all you need to know!

cactustictacs
  • 17,935
  • 2
  • 14
  • 25
  • Could you tell me this `container` where and with what will fill? – Mohammad Feb 11 '22 at 18:22
  • I came to the conclusion that `container` in this method is null !! because I saw the log in below source code: – Mohammad Feb 11 '22 at 20:28
  • `@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if(container == null){ Log.i("Container", "Container is null !"); //After run, I see this log. so container parameter is null! } return inflater.inflate(R.layout.fragment_latout, container, false); }` – Mohammad Feb 11 '22 at 20:32
  • if `container` is always null, so why there is in this method?! – Mohammad Feb 11 '22 at 20:33
  • @Mohammad It's not always null, e.g. if you have a ``FrameLayout`` container in an ``Activity``, and you use a ``FragmentTransaction`` to ``add`` your Fragment to that container view, then that ``FrameLayout`` will be passed in as ``container``. So if there's something special you need to do with it, you can. Usually you just pass it to the inflater, whether it's null or not – cactustictacs Feb 12 '22 at 17:45
  • Oh! your right! I thought that container is always null. so if we add a fragment in the activity by `FragmentTransaction`, `container` will not be null. Thanks – Mohammad Feb 12 '22 at 18:36