Best practice for nested fragments in Android 4.0, 4.1 (

Limitations

So nesting fragments inside another fragment is not possible with xml regardless of which version of FragmentManager you use.

So you have to add fragments via code, this might seem like a problem, but in the long run makes your layouts superflexible.

So nesting without using getChildFragmentManger? The essence behind childFragmentManager is that it defers loading until the previous fragment transaction has finished. And of course it was only naturally supported in 4.2 or the support library.

Nesting without ChildManager – Solution

Solution, Sure! I have been doing this for a long time now, (since the ViewPager was announced).

See below; This is a Fragment that defers loading, so Fragments can be loaded inside of it.

Its pretty simple, the Handler is a really really handy class, effectively the handler waits for a space to execute on the main thread after the current fragment transaction has finished committing (as fragments interfere with the UI they run on the main thread).

// Remember this is an example, you will need to modify to work with your code
private final Handler handler = new Handler();
private Runnable runPager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    return inflater.inflate(R.layout.frag_layout, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    runPager = new Runnable() {

        @Override
        public void run()
        {
          getFragmentManager().beginTransaction().addFragment(R.id.frag_container, MyFragment.newInstance()).commit();
        }
    };
    handler.post(runPager);
}

/**
 * @see android.support.v4.app.Fragment#onPause()
 */
@Override
public void onPause()
{
    super.onPause();
    handler.removeCallbacks(runPager);
}

I wouldn’t consider it ‘best practice’, but I have live apps using this hack and I am yet to have any issues with it.

I also use this method for embedding view pagers – https://gist.github.com/chrisjenx/3405429

Leave a Comment