ViewPager/FragmentPageAdapter, after recreation, does not call onCreate() of last selected view - android

I am currently working on an application with ActionBar tabs inside one of its fragments (main navigation is NavigationDrawer). The fragment's onCreate():
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
actionBar = activity.getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Resources r = getResources();
//(…) tabNames initialization
adapter = new CustomTabAdapter(getFragmentManager());
}
and onCreateView():
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(this);
for (String tabName : tabNames) {
actionBar.addTab(actionBar.newTab()
.setText(tabName)
.setTabListener(this));
}
return rootView;
}
There are 4 tabs, each of them with its own Fragment and layout. CustomTabAdapter returns new instance of proper fragment in its getItem(int). There are 4 tabs.
And now my problem is:
I start the application.
I choose this tab fragment from NavigationDrawer list. Everything is working just fine.
I choose another fragment from NavigationDrawer list which means that tab fragment is replaced with it.
I choose tab fragment again. And fragment related to tab that was selected before choosing another fragment from NavigationDrawer list, and one's adjacent to it are not recreated (blank screen under ActionBar tabs). I checked and onCreateView(…) methods of those fragment are not called. So after changing device orientation, or choosing tab not adjacent and this one again proper layout is shown.
How can I make it work as it should (showing proper layout on reentering tab fragment from NavigationDrawer list instead of blank space)? I run out of ideas.

Finally, I found a solution. My CustomTabAdapter was extension of FragmentPagerAdapter. I changed it to be extension of FragmentStatePageAdapter, and now fragments are recreated.
More details in this answer by #Louth.

It takes fragments from cache without recreation

Related

ViewPager setOffscreenPageLimit not working when using it as NestedFragment with getChildFragmentManager

I am trying to do something similar as https://stackoverflow.com/a/24437224/2277631. I am even using the same layout:
I am following this approach because I am using a NavigationView (each option is a fragment) that has the first option as a fragment with Tabs (so a ViewPager with more fragments).
I found a problem when using:
viewPager.setAdapter(new AdapterView(getChildFragmentManager()));
Basically, using the ViewPager as nested fragment, it only loads 1 page (from the 3 tabs), and it only loads the other pages when I swipe to them (each tab is a fragment with its ContentLoader). I found that using setOffscreenPageLimitgets ignored in this case. Instead, if I use:
getActivity().getSupportFragmentManager() then the ViewPager works as expected (loading by default 1 page and the next and previous pages). But then, a lot of weird stuff happen (cause I am suppose to use getChildFragmentManager when using nested fragments). So... Any ideas of using ViewPager as nested fragment and make setOffscreenPageLimit to work?
Edit 1 (30 Dec 15)
Tracking the bug down, I checked that all the fragments are been created. The problem is that the three fragments have they own LoaderCallback but only the first one calls onLoadFinished. Trying to figure out why the other fragments only call onLoadFinished when navigating to it (was working without the nested approach).
I ran into the same problem. This is how I do and this is working for me, it has the same architetcure as what you expect to have.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
view = inflater.inflate(R.layout.communitylayout, container, false);
Bundle data = getArguments();
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.comtabs);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
// add tabs
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
RelativeLayout layout1 = (RelativeLayout) inflater.inflate(R.layout.communitytablayoutleft, container, false);
RelativeLayout layout2 = (RelativeLayout) inflater.inflate(R.layout.communitytablayout, container, false);
RelativeLayout layout3 = (RelativeLayout) inflater.inflate(R.layout.communitytablayoutright, container, false);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
pager = (ViewPager) view.findViewById(R.id.compager);
CommunityPagerFragment adapter = new CommunityPagerFragment(getChildFragmentManager());
pager.setAdapter(adapter);
tabLayout.setupWithViewPager(pager);
pager.setCurrentItem(0);
tabLayout.setOnTabSelectedListener(this);
// KEEP FRAGMENT STATE INSIDE OF THE TAB
pager.setOffscreenPageLimit(2);
((TextView)layout1.findViewById(R.id.tabtext)).setText(tabs[0]);
((TextView)layout2.findViewById(R.id.tabtext)).setText(tabs[1]);
((TextView)layout3.findViewById(R.id.tabtext)).setText(tabs[2]);
//tabLayout.set
tabLayout.getTabAt(0).setCustomView(layout1);
tabLayout.getTabAt(1).setCustomView(layout2);
tabLayout.getTabAt(2).setCustomView(layout3);
onTabSelected(tabLayout.getTabAt(1));
//tabLayout.set
return view;
And if you want to get the Tabs working by click in addition of the swipe, add the following:
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}

Handling the backstack with fragments containing tabs

I'm trying to create an Android application which contains a single activity with a container and a navigation drawer. The initialy empty container loads fragments which has a ViewPager inside a tab layout in which I load a frgment with a FragmentTransaction:
public static void replaceFragmentInContainer(FragmentManager fragmentManager, Fragment fragmentToShow,
boolean addToBackStack)
{
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (addToBackStack)
{
transaction.addToBackStack(null);
}
transaction.replace(R.id.container, fragmentToShow);
transaction.commit();
}
I'm using v4 fragments with a v7 ActionBar in a v7 ActionBarActivity.
Every loaded fragment is a fragment which only loads tabs with other fragments which they hold the actual usability. An example of such tab loading fragment:
public class MainFragment extends TabsFragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View contentView = inflater.inflate(R.layout.fragment_main, container, false);
initTabsLayout(savedInstanceState, contentView, R.id.pager);
addTab("tabspectag1", "", R.drawable.draw1, Fragment1.class, null);
addTab("tabspectag2", "", R.drawable.draw2, Fragment2.class, null);
addTab("tabspectag3", "", R.drawable.draw3, Fragment3.class, null);
return contentView;
}
The problem I'm facing is with the backstack. When a fragment is added to the backstack and I press the back button, the app does go back to the previous fragment like I want to and I see the tabs layout itself, but the content of the tabs is empty like there was nothing loaded to that tab. When it happens, I manage to reload the tab's content only when choosing that screen again with the navigational drawer.
I've tried overriding the onBackPressed in the activity:
#Override
public void onBackPressed()
{
if (getFragmentManager().getBackStackEntryCount() > 0)
{
getFragmentManager().popBackStack();
} else
{
super.onBackPressed();
}
}
but that like I said, it's like I'm getting back to the previous fragment but the tab inside that fragment is not repainting the fragment it had.
What can be done to solve this issue?
Since I DO see the tabs layout of the original fragment in the backstack but not the fragment inside the tab, is it possible I just need to somehow refresh the tab content meaning repaint it? If I can do such a thing then how can I do it?
You didn't post the entire code but, bear in mind that when using fragments inside fragments, the outer fragment should use the childfragmentmanager instead of the regular fragment manager.
If you have an Activity, then you have a fragment that has a Viewpager and inside that viewpager the views are fragments, those outer fragments must use their own childfragmentmanager instead of the activities fragmentmanager.
Activity uses getFragmentManager() to instantiate and show new fragments. Fragments use getChildFragmentManager() to instantiate and show new inner fragments. (fragments inside fragments).
If you always use the same fragmentmanager to handle the transactions the behaviour will be unpredictable.
Your Viewpager should have an TabsAdapter associated that extends from FragmentStatePagerAdapter to show new fragments(and uses the getChildFragmentManager from the fragment instead of the activity).

Fragment within FragmentTabHost view lost onBackPressed Android?

I have created a application. Following is scenario before I explain problem.
I have Activity A which has multiple fragments such as F1,F2,F3 etc.
Now for F1 fragment I have implemented FragmentTabHost with three Fragments F11,F12,F13 fragment views. On tab is working fine for this.
But today i noticed one problem.
Say I am inside F1 I show three fragment tabs F11,F12,F13. User can switch between tabs and it works fine.
Problem is say i goto Fragment F13 from F11 by pressing tab. It shows F13 fragment successfully.
However when I click Back Button on menu it goes back F11 fragment but empty screen is shown means F11 view is not shown..
This is my F1 fragment code implementing FragmentTabHost:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_fragment, container,
false);
setHasOptionsMenu(true);
// realtabcontent = (FrameLayout) rootView
// .findViewById(R.id.realtabcontent);
mTabHost = (FragmentTabHost) rootView
.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(),
R.layout.home_fragment);
mTabHost.setOnTabChangedListener(this);
View tabView = createTabView(getActivity(), "Featured");
spec = mTabHost.newTabSpec("featured").setIndicator(tabView);
mTabHost.addTab(spec, FeaturedHomeTab.class, null);
tabView = createTabView(getActivity(), "Top");
spec = mTabHost.newTabSpec("top").setIndicator(tabView);
mTabHost.addTab(spec, TopHomeTab.class, null);
tabView = createTabView(getActivity(), "New");
spec = mTabHost.newTabSpec("new").setIndicator(tabView);
mTabHost.addTab(spec, NewHomeTab.class, null);
onTabChanged("featured");
return rootView;
}
So this is main code with three fragments and when i back from one fragment to previous fragment in tabhost view disappears.
What can be problem. Please help.
Tabs aren't meant to participate in temporal navigation (which is what back nav is for) because they represent content at same level of hierarchy.
In case of fragments, the back nav usually pops the back stack. There is a caveat that back nav doesn't pops sub (child) fragments first. So, the fragments added to Activity are removed on back, this includes the entire tabs fragment (along with its child fragments).

Fragment view in ViewPager is not restored when resuming

I have ActionBar Tabs setup. It consists of 4 tabs. Everything is fine until I navigate away from TabbedFragment and returning back.
I create tabs like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getActionBar();
tabs = Lists.newArrayList();
tabs.add(new TabDefinition<>("Tab 1"));
tabs.add(new TabDefinition<>("Tab 2"));
tabs.add(new TabDefinition<>("Tab 3"));
tabs.add(new TabDefinition<>("Tab 4"));
for (TabDefinition tab : tabs) {
actionBar.addTab(actionBar.newTab()
.setText(tab.text)
.setTag(tab.tag)
.setTabListener(this));
}
}
And initialize adapter like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.paging_tab_container, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager = (ViewPager) view.findViewById(R.id.pager);
viewPager.setAdapter(new FragmentStatePagerAdapter(getFragmentManager()) {
#Override
public Fragment getItem(int position) {
return tabs.get(position).fragment;
}
#Override
public int getCount() {
return tabs.size();
}
});
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
getActionBar().setSelectedNavigationItem(position);
}
});
viewPager.setCurrentItem(getActionBar().getSelectedNavigationIndex(), true);
}
When returning back to TabbedFragment selected tab and 1 next to it would not have any content. Just empty view. But if I select current + 2 fragment content is loaded. And then returning to that first fragment content is reloaded.
For example I have A, B, C, D tabs. Before leaving TabbedFragment I had selected tab A.
When returning to TabbedFragment I still am at tab A, but it's empty. So is tab B.
But when selecting tab C it is created and loaded. Returning to tab A it is recreated.
What could be the problem here?
After a while ran into the same problem again, so updating this question.
If you're using FragmentStatePagerAdapter you should provide FragmentManager via getChildFragmentManager() instead of getFragmentManager(). See Issue 55068: ViewPager doesn't refresh child fragments when back navigation via backstack
Okay so When using a FragmentStatePagerAdapter your fragments will be destroyed when you navigate anymore than one fragment Away since by default offScreenPageLimit is set to 1 by default just as mentioned above.
Typically this Class is used for an activity that has a very large set of Fragments, i.e have to scroll through a large amount of views. If your application does not need more than say 3-4 tabs I would suggest using FragmentPagerAdapter instead, and then specifying your offScreenPageLimit to something like 3, so if you get to the 4th Tab, all 3 tabs before will still be in memory.
Here is some Sample Code for a project on github that i created illustrating how to dynamically load the fragments if you don't want to add this offScreenPageLimit.
https://github.com/lt-tibs1984/InterfaceDemo/blob/master/src/com/divshark/interfacedemo/InterfaceDemoMain.java
Walk through all this code in this Class, and you will see how I'm dynamically loading the fragments, each time my ViewPager is slid over. Most notably at the bottom.
You can download this code, and use it as a test base for what you want to do.
Try adding the setOffScreenPageLimit(2) in the onCreate() method for the viewPager and notice the different behavior. To check the behavior, edit the text in fragment 1. Navigate Away and navigate back, with this set or not. You will see when it is set, the fragment's text remains what you change it to, since the fragment is never recreated.
Please provide additional questions if you have them.
GoodLuck
UPDATE
private static final String [] fragmentClasses = {"com.example.project.YourFragment1","com.example.project.YourFragment2","com.example.project.YourFragment3"};
viewPager.setAdapter(new FragmentStatePagerAdapter(getFragmentManager()) {
#Override
public Fragment getItem(int position) {
Fragment fragmentAtPosition = null;
// $$$$ This is the Important Part $$$$$
// Check to make sure that your array is not null, size is greater than 0 , current position is greater than equal to 0, and position is less than length
if((fragmentClasses != null) && (fragmentClasses.length > 0)&&(position >= 0)&& (position < fragmentClasses.length))
{
// Instantiate the Fragment at the current position of the Adapter
fragmentAtPosition = Fragment.instantiate(getBaseContext(), fragmentClasses[position]);
fragmentAtPosition.setRetainInstance(true);
}
return fragmentAtPosition;
}
#Override
public int getCount() {
return fragmentClasses.length;
}
});
The problem exists in the Fragments you use as tabs, I think. They seem to not show anything when they are resumed (see Fragment lifecycle). The "weird" issue that only the currently selected +/-1 tab is empty, is because the offScreenPageLimit of your ViewPager is 1 by default. All tabs above this threshold are re-created.
Therefore, increasing the value will -- in your case -- cause all your tabs to appear empty after resuming. Check in your Fragment code which lifecycle methods you use to inflate your layout, set adapters and so forth, because that's what's causing your trouble.
I guess this happens because while loading fragment android loads current and current+1, if you debug you would not see onPause getting called for the immediate next fragment.
You can reload content programmatically in onTabChanged() method of TabHost.OnTabChangeListener.
After doing much research, this worked for me.
I have a complex layout with 3 tabs in a fragment, that gets switched out for other fragments. I realized that the ViewpagerAdapter will retain state, even if you press the home button. My problem was switching back and forth would null out the child fragment UI view elements and crash. The key is to not new out your ViewPagerAdapter. Adding the null check for the Adapter worked for me. Also, be sure to allocate setOffscreenPageLimit() for your needs. Also, from what I understand setRetainInstance(true); should not be used for fragments that have UI, it is designed for headless fragments.
In the fragment that holds your Tabs:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab, container, false);
tabLayout = (TabLayout) view.findViewById(R.id.tablayout);
viewPager = (ViewPager) view.findViewById(R.id.viewPager);
//Important!!! Do not fire the existing adapter!!
if (viewPagerAdapter == null) {
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPagerAdapter.addFragments(new AFragment(), "A");
viewPagerAdapter.addFragments(new BFragment(), "B");
viewPagerAdapter.addFragments(new CFragment(), "C");
}
//Allocate retention buffers for three tabs, mandatory
viewPager.setOffscreenPageLimit(3);
tabLayout.setupWithViewPager(viewPager);
viewPager.setAdapter(viewPagerAdapter);
return view;
}
Or more simply when navigating back to tabbedfragment (assuming you use an intent and the fragment is within an activity) use:
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This keeps the original activity and moves it to the top of the stack rather than recreating it, thus you never need to recreate the viewPager.

Android FragmentTab host and Fragments inside Fragments

I have an app with hierarchy like this:
FragmentTabHost (Main Activity)
- Fragment (tab 1 content - splitter view)
- Fragment (lhs, list)
- Framment (rhs, content view)
- Fragment (tab 2 content)
- Fragment (tab 2 content)
All fragment views are being inflated from resources.
When the app starts everything appears and looks fine. When I switch from the first tab to another tab and back again I get inflate exceptions trying to recreate tab 1's views.
Digging a little deeper, this is what's happening:
On the first load, inflating the splitter view causes its two child fragments to be added to the fragment manager.
On switching away from the first tab, it's view is destroyed but it's child fragments are left in the fragment manager
On switching back to the first tab, the view is re-inflated and since the old child fragments are still in the fragment manager an exception is thrown when the new child fragments are instantiated (by inflation)
I've worked around this by removing the child fragments from the fragment manager (I'm using Mono) and now I can switch tabs without the exception.
public override void OnDestroyView()
{
var ft = FragmentManager.BeginTransaction();
ft.Remove(FragmentManager.FindFragmentById(Resource.Id.ListFragment));
ft.Remove(FragmentManager.FindFragmentById(Resource.Id.ContentFragment));
ft.Commit();
base.OnDestroyView();
}
So I have a few questions:
Is the above the correct way to do this?
If not, how should I be doing it?
Either way, how does saving instance state tie into all of this so that I don't lose view state when switching tabs?
I'm not sure how to do this in Mono, but to add child fragments to another fragment, you can't use the FragmentManager of the Activity. Instead, you have to use the ChildFragmentManager of the hosting Fragment:
http://developer.android.com/reference/android/app/Fragment.html#getChildFragmentManager()
http://developer.android.com/reference/android/support/v4/app/Fragment.html#getChildFragmentManager()
The main FragmentManager of the Activity handles your tabs.
The ChildFragmentManager of tab1 handles the split views.
OK, I finally figured this out:
As suggested above, first I changed the fragment creation to be done programatically and had them added to the child fragment manager, like so:
public override View OnCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstance)
{
var view = inflater.Inflate(Resource.Layout.MyView, viewGroup, false);
// Add fragments to the child fragment manager
// DONT DO THIS, SEE BELOW
var tx = ChildFragmentManager.BeginTransaction();
tx.Add(Resource.Id.lhs_fragment_frame, new LhsFragment());
tx.Add(Resource.Id.rhs_fragment_frame, new RhsFragment());
tx.Commit();
return view;
}
As expected, each time I switch tabs, an extra instance of Lhs/RhsFragment would be created, but I noticed that the old Lhs/RhsFragment's OnCreateView would also get called. So after each tab switch, there would be one more call to OnCreateView. Switch tabs 10 times = 11 calls to OnCreateView. This is obviously wrong.
Looking at the source code for FragmentTabHost, I can see that it simply detaches and re-attaches the tab's content fragment when switching tabs. It seems the parent Fragment's ChildFragmentManager is keeping the child fragments around and automatically recreating their views when the parent fragment is re-attached.
So, I moved the creation of fragments to OnCreate, and only if we're not loading from saved state:
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
if (savedInstanceState == null)
{
var tx = ChildFragmentManager.BeginTransaction();
tx.Add(Resource.Id.lhs_fragment_frame, new LhsFragment());
tx.Add(Resource.Id.rhs_fragment_frame, new RhsFragment());
tx.Commit();
}
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstance)
{
// Don't instatiate child fragments here
return inflater.Inflate(Resource.Layout.MyView, viewGroup, false);
}
This fixed the creation of the additional views and switching tab's basically worked now.
The next question was saving and restoring view state. In the child fragments I need to save and restore the currently selected item. Originally I had something like this (this is the child fragment's OnCreateView)
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
var view = inflater.Inflate(Resource.Layout.CentresList, container, false);
// ... other code ommitted ...
// DONT DO THIS, SEE BELOW
if (savedInstance != null)
{
// Restore selection
_selection = savedInstance.GetString(KEY_SELECTION);
}
else
{
// Select first item
_selection =_items[0];
}
return view;
}
The problem with this is that the tab host doesn't call OnSaveInstanceState when switching tabs. Rather the child fragment is kept alive and it's _selection variable can be just left alone.
So I moved the code to manage selection to OnCreate:
public override void OnCreate(Bundle savedInstance)
{
base.OnCreate(savedInstance);
if (savedInstance != null)
{
// Restore Selection
_selection = savedInstance.GetString(BK_SELECTION);
}
else
{
// Select first item
_selection = _items[0];
}
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
// Don't restore/init _selection here
return inflater.Inflate(Resource.Layout.CentresList, container, false);
}
Now it all seems to be working perfectly, both when switching tabs and changing orientation.

Categories

Resources