0

I have a Fragment which implements FragmentTabHost and creates a couple of tabs each of which has a Fragment. I am trying to get a reference to one of these Fragments, but am drawing a blank as to how.

public class TabFragment extends Fragment {
    private FragmentTabHost mTabHost;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.container);

        addTab("study","Study",StudyFragment.class);
        addTab("tab2","Tab 2",Tab2Fragment.class);

        return mTabHost;
    }

    private <T extends Fragment> void addTab(String sTag, String sTitle, Class<T> c) {
        View tabView = createTabView(getActivity(),sTitle);

    mTabHost.addTab(mTabHost.newTabSpec(sTag).setIndicator(tabView),
                    c, null);
    }

    public StudyFragment getStudyFragment() {
        // not working as fragment has not been tagged
        return getChildFragmentManager().findFragmentByTag("study");
    }

So the question is how do I either tag the study fragment or return a reference to it when it is created?

I've seen a couple of solutions which suggest overriding onAttachFragment, but that is for FragmentActivity not Fragment

QuantumTiger
  • 970
  • 1
  • 10
  • 22

2 Answers2

1

To get a fragment, you can set an id to your fragment, then use this:

FragmentManager manager = getSupportFragmentManager();
MyFragment myFragment = (MyFragment)manager.findFragmentById(R.id.MyFragment);
Maxime
  • 1,332
  • 1
  • 15
  • 43
  • 1
    I know that. The issue is that as the fragment is being created for me by the FragmentTabHost I can't see how to either add an id or a tag to the fragment – QuantumTiger Nov 26 '14 at 15:30
-1

Ok so you have to add tabs using TabHost.TabSpec like that:

tabHost = (FragmentTabHost)mainView.findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

TabHost.TabSpec tabOne = tabHost.newTabSpec("One").setContent(R.id.fragOne);
TabHost.TabSpec tabTwo = tabHost.newTabSpec("Two").setContent(R.id.fragTwo);

tabHost.addTab(tabOne, TabOne.class, savedInstanceState);
tabHost.addTab(tabTwo, TabTwo.class, savedInstanceState);

In this code R.id.fragOne and R.id.fragTwo refers to two FrameLayout defined in the activity layout. If you dont have xml layout you can define programmatically a new FrameLayout with an id for each tab.

Maxime
  • 1,332
  • 1
  • 15
  • 43