Search code examples
androidandroid-fragmentsandroid-tabhost

Communicate with a fragment in a FragmentTabHost


I want to communicate with a fragment in a FragmentTabHost

The communication Fragment->Activity is done! With an interface.

But I can't create a communication Activity->Fragment because I created the fragment like this:

mTabHost.addTab(
            mTabHost.newTabSpec("tab2").setIndicator("Affichage",
                    getResources().getDrawable(android.R.drawable.star_on)),
            MySelectionFragment.class, null);

MySelectionFragment is a class not a fragment like new MySelectionFragment()

And I dunno how to communicate with a class :/

Thanks in advance!


Solution

  • The trick was to override the onAttach method like this:

    @Override
    public void onAttachFragment(android.support.v4.app.Fragment attachedFragment) {
        super.onAttachFragment(attachedFragment);
    
        if (attachedFragment.getClass().equals((ObjectA.class)) {
            mObjectA = (ObjectA)attachedFragment;
        }
        if (attachedFragment.getClass().equals((ObjectB.class)) {
            mObjectB = (ObjectB) attachedFragment;
        }
    }