Reputation: 3548
The basic architecture of my app is that I show a loading screen in the 3 screens of a ViewPager
while loading some data(3 fragments for the 3 screens) and when the data has been loaded I show 3 new fragments, replacing the old fragments in all the screens of the ViewPager
.
root_frameview.xml (This contains the fragment in each of the screen of the viewpager):-
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/root_view">
</FrameLayout>
Now, in the adapter class of ViewPager
, the Fragment getItem(int position)
method is :-
@Override
public Fragment getItem(int position) {
Fragment f = new Fragments();
pageFragments.add(f);//pageFragments is an ArrayList keeping track of all the added fragments
return f;
}
And the Fragments class is
public static class Fragments extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.root_frameview, container, false);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.root_view, new LoadingFragment());//the loading page fragment
transaction.commit();
return rootView;
}
public void replace() {
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.root_view, new LoadedFragment());//the loaded fragment
transaction.commit();
}
}
Note, that it has a replace()
method which I call when the data has been loaded to replace the fragment(loading page - LoadingFragment
) with the other fragment - LoadedFragment
.
And this is the screen which has been loaded :-
Seems perfectly fine, huh? But the problem starts here:- When I swipe to TAB 2 and come back to TAB 1 , the same loading screen appears as shown in image 1. It does not even loads anything now, just the layout is shown. Where am I going wrong?
Upvotes: 0
Views: 56
Reputation: 5061
Please set setOffscreenPageLimit for the view pager by simply adding this code
pager.setOffscreenPageLimit(3);
For a view page the setOffscreenPageLimit is default is 0 so the next page is loaded . when you move to the tab3 ,tab 1 is killed and it will again called the on createview when you swipe to tab1 . This can be solved in change the setOffscreenPageLimit
Upvotes: 1