Nested Fragments in Android

Audio : Listen to This Blog.

Fragments represent a behavior or portion of UI in an Activity. Fragments are mostly used in tablets to divide screen and utilize screen space in efficient way.

App Development Company

With Android 4.2 nested fragments are introduced, with which now you can embed fragments inside fragments. This is useful for a variety of situations in which you want to place dynamic and re-usable UI components into a UI component that is itself dynamic and re-usable. For example, if you use ViewPager to create fragments that swipe left and right and consume a majority of the screen space, you can now insert fragments into each fragment page.
To nest a fragment, simply call getChildFragmentManager() on the Fragment in which you want to add a fragment. These returns a FragmentManager that you can use like you normally do from the top-level activity to create fragment transactions. For example, here’s some code that adds a fragment from within an existing Fragment class:

Fragment videoFragment = new VideoPlayerFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.video_fragment, videoFragment).commit();
From within a nested fragment, you can get a reference to the parent fragment by calling getParentFragment().
The Android Support Library also now supports nested fragments, so you can implement nested fragment designs on Android 1.6 and higher.

Note:

You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically.

Read Similar Blogs