Reputation: 185
I am trying to retrieve a fragment from my fragmentTabHost:
private void initView() {
FragmentTabHost mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("summary").setIndicator("Summary"),
SummaryActivity.class, bundle);
SummaryActivity summaryActivity = (SummaryActivity) getSupportFragmentManager().findFragmentByTag("summary");
System.out.println(summaryActivity);
}
When I try to get my fragment immediately after it was created, it returns null. It could be a thread issue. How, or even when, should I call getFragmentByTag to retrieve my fragment in this case?
Upvotes: 1
Views: 878
Reputation: 3221
The Fragment
you are looking for is not in the stack. It is not even added/present at the time you are finding it back.
findFragmentByTag
method will look and match last fragment that added in the transaction, if that is not matching with the required one, then it will search with the available list from history. Finally if your tag is not there with any fragments it will return null
.
Make sure that , you are adding the Fragment
to the view first.
the view should receive the fragment/tabhost to make it available in the lifecycle.
you have to return your tabHost
to the view to add the fragment before you do findFragmentByTag
lookup.
For ex:
You are in your Fragment
's onCreateView
then you should do return the tabhost
to the view after you inflated it.
onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.fragment1);
mTabHost.addTab(mTabHost.newTabSpec("fragmenttag").setIndicator("Fragmenttag"),
FragmentStackSupport.CountingFragment.class, null);
return mTabHost;
}
Then probably your Fragment
will be available in back stack , you can get it back by Tag
.
Upvotes: 2
Reputation: 146
Fragment Tags can only be set during fragment transactions. The tab host tag refers to something else. Try using findFragmentById() if you set an id on the fragments root view.
Upvotes: 0