Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting reference to nested fragment from FragmentTabHost

In my application, I use an Activity which holds one Fragment with FragmentTabHost and hence all its tabs are nested Fragments.

Inside an Activity which holds a Fragment with its nested Fragment, we may get a reference to attached one using onAttachedFragment().

But how to get a reference to nested Fragment from FragmentTabHost?

like image 237
Alex Bonel Avatar asked Apr 09 '13 09:04

Alex Bonel


3 Answers

Well, exploring the source code of FragmentTabHost I've found that when it adds a fragment tab, it assignes a tag of TabSpec to nested Fragment.

So to get the reference to this Fragment we should call

getChildFragmentManager().findFragmentByTag(tabSpecTag)

like image 125
Alex Bonel Avatar answered Nov 07 '22 04:11

Alex Bonel


I was trying this for a while, but I was getting null returned from the FragmentManager because I was trying to access the manager in onCreateView() immediately after adding.

Here is a good explanation on what happened

It's also important to note that Fragment tabs that have not yet been selected don't exist yet in the FragmentManager, and so will return null as well. I got around this by calling mTabHost.setCurrentTab(index) before trying get to the Fragment with the FragmentManager. It's not very clean, but it works.

like image 22
loadedion Avatar answered Nov 07 '22 04:11

loadedion


Above solutions are also working but I have one more easy solution,

 @Override
public void onTabChanged(final String tabId) {

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            mFragment = getChildFragmentManager().findFragmentByTag("Tagname");
        }
    },1000);
}

Here you have to implement FragmentTabHost.onTabChangeListener We have kept a second delay in fetching fragment from the childFragmentManager.

Note : You need to cast mFragment which fragment you have used.

like image 35
Nirav Shah Avatar answered Nov 07 '22 04:11

Nirav Shah