I'm using 3 Fragments
inside a Viewpager
, the problem is that I am loading big data in an Asynctask
and loaders. On devices like HTC one
, it works fine, however, on low-end devices, it takes a lot of time. This is mainly because when I implement the pagerAdapter
, I put the Fragments inside an ArrayList
, this force the fragments instantiate when the main activity is loaded. What I need is that it just "load" the first fragment (main) and when the user Swype
, load the other fragment. its any way to achieve this? this is my pageAdapater
public class PagerAdapter extends FragmentPagerAdapter {
private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
// private final ArrayList<String> titulos = new ArrayList<String>();
// private int NUM_PAGES =0;
public PagerAdapter(FragmentManager manager,int num_pages) {
super(manager);
// this.NUM_PAGES = num_pages;
}
public void addFragment(Fragment fragment,String title) {
mFragments.add(fragment);
notifyDataSetChanged();
}
@Override
public int getCount() {
//return NUM_PAGES;
return mFragments.size();
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
}
Use fragmentStatePageAdapter if you have a lot of pages and you want to destroy them when not visible. It has implemented a setMenuVisibility(boolean menuVisible) when fragment becomes visible, so use that.
The above method from Sun did not work for me (maybe it does for you), but I thought I would share my edit of his method also. Very good method by the way Sun!
Slightly modified version to fix potential NPE caused by some views not fully initialised
I might be late for the party but here's my solution and it works as expected. In all of your child fragments create a
boolean
variable:in the child fragments create a generic method called
loadFragment
and move all of the logic you added inonCreateView
to that method:in your pageview logic create the fragments dynamically like:
then set your pager adapter and attach a tablayout with it:
I'm gonna add my solution here since I faced a similar issue. My asynchronous task wasn't loading huge amounts of data, but it prevents unnecessary network calls. Here's what I added in my Fragment:
With the above code, your Fragment will be loaded, but your async task will not run until the user actually scrolls to the Fragment for the first time. Once displayed, your async task will run for the first time automatically. Then you can provide a way to load more data via a button or pull to refresh. The above Fragment was in my ViewPager and seemed to work fine.