FragmentTabHost not creating view inside Fragment in android

shaneburgess picture shaneburgess · Jan 11, 2014 · Viewed 7.8k times · Source

I am having an issue getting the view to change on a tabhost - when I select a tab the content stays blank.

From what I can tell, onCreateView is not being called on the child Fragments. onMenuCreate runs fine because the menu changes like it is supposed to.

   public class PatientTabFragment extends Fragment {
    private FragmentTabHost mTabHost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager());

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Info"),
                NewPatientFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Notes"),
                NoteListFragment.class, null);


        return mTabHost;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mTabHost = null;
    }
}

Answer

Rafael T picture Rafael T · Jan 11, 2014

according to the docs:

Special TabHost that allows the use of Fragment objects for its tab content. When placing this in a view hierarchy, after inflating the hierarchy you must call setup(Context, FragmentManager, int) to complete the initialization of the tab host.

(emphasis mine)

So I suggest somethong like this:

   public class PatientTabFragment extends Fragment {
    private FragmentTabHost mTabHost;
    private boolean createdTab = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager());

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Info"),
                NewPatientFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Notes"),
                NoteListFragment.class, null);


        return mTabHost;
    }

    public void onResume(){
        if (!createdTab){
          createdTab = true;
          mTabHost.setup(getActivity(), getActivity().
                         getSupportedFragmentManager());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mTabHost = null;
    }
}