Search code examples
javaandroidandroid-fragmentsandroid-fragment-manager

Does findFragmentById take in a FrameLayout rather than a Fragment?


I'm new to the concept of Fragments

In the video I was watching, they used this piece of code:

FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment fragment = fragmentManager.findFragmentById(R.id.my_container);

        if(fragment == null){
            fragment = new FragmentMain();
            fragmentManager.beginTransaction()
                    .add(R.id.my_container, fragment)
                    .commit();
        }

To create a Fragment via java.

  1. In findFragmentById they passed in a FrameLayout(my_container) rather than a Fragment. I read in the docs that you can pass in a container id, but it confuses me how it will initialize it as a Fragment. How does this work?

  2. Should I use FragmentManager? I read in the docs that it's deprecated.

Thanks!


Solution

  • In findFragmentById they passed in a FrameLayout(my_container) rather than a Fragment. I read in the docs that you can pass in a container id, but it confuses me how it will initialize it as a Fragment. How does this work?

    You can think of the container as of a placeholder that can hold a fragment at a time; initially it has no fragment and in this case the if(fragment == null) will be met, so you can do a fragment transaction (So, the container layout now is replaced by a fragment view, which is another xml layout assigned to this particular fragment and returned by its onCreateView() callback.onCreateView() is one of fragment's lifecycle callbacks that get called by the system until the fragment is fully visible to the user in the placeholder.

    Later on when you want this placeholder to hold another fragment, you can do the transaction again where it repeats the same thing with the new fragment, the placeholder will show up the layout of the new fragment, and the lifecycle methods of this fragment will get called

    Should I use FragmentManager? I read in the docs that it's deprecated.

    FragmentManger (from android.app package) and its getFragmentManager() are deprecated, and you should use FragmentManager (from androidx.fragment.app package) and getSupportFragmentManager() instead like you already did.

    For more info you can have a look to FragmentManager doc and Fragment lifecycle.