Getting reference to nested fragment from FragmentTabHost

匆匆过客 提交于 2019-12-03 06:00:54

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)

loadedion

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.

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.

I found a solution that I like a little better because it doesn't involving executing code with a delay (which is always iffy given android hardware fragmentation and different processor speeds).

In your onTabChanged() method, before you try to find the fragment, call executePendingTransactions() on the fragment manager associated with your tabHost. It seems there are some places in the FragmentTabHost source code where they should be calling executePendingTransactions() but fail to do so.

This works every time the tab changes with one exception... the first tab that is selected still comes back null... In my specific case, I was able to handle this exception differently anyway, by putting some code in onResume.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!