Reputation: 515
My viewpager is set with offscreenpagelimit 1 (default)
When i scroll my viewpager to the right, oncreateview is called on the fragment with the current position +1 to prepare the next fragment.
But when i swipe to the 3rd fragment and go back to the second, the first fragment's oncreateview is not called.
Why is the viewpager behaving like this and how can i preload previous fragments if they were removed from memory?
Upvotes: 1
Views: 2919
Reputation: 1015
The viewPager behaves like this because the fragmentStatePagerAdapter is saving its views. On the first run, you will alyways see the onCreateView() is called for the n+1 fragment. But if you have swiped over all the Fragments, their views are already in the FragmentStatePagerAdapter. Of course, is could happen that the PagerAdapter will destroy some views(and the Fragment) because of memmory management reasons.
Lets assume this happens: the fragment X gets destroyed. So if you swipe over you fragments, and you are on fragment Y. fragment X is in your offscreenpagelimit. The FragmentStatePagerAdapter will notice that there is no fragment availible and will recreate it. In this case, the onCreateView() will be called again.
If you want to preload the state, which was before the Fragment got destroyed, then you need to use the callback onSaveInstanceState().
Here is an example:
to save the state of the Fragment:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.v(TAG, "In frag's on save instance state ");
outState.putSerializable("starttime", startTime); //saves the object variable
}
to restore the state:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.v(TAG, "In frag's on create view");
View view = inflater.inflate(R.layout.fragment_data_entry, container,
false);
timeTV = (TextView) view.findViewById(R.id.time_tv);
if ((savedInstanceState != null)
&& (savedInstanceState.getSerializable("starttime") != null)) {
startTime = (Calendar) savedInstanceState
.getSerializable("starttime");
}
return view;
}
This code is taken from here. You get more information about this on this site.
Upvotes: 1