Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how load fragment in ViewPager only when its selected

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);

    }

} 
like image 834
Javier Avatar asked Oct 21 '13 03:10

Javier


1 Answers

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!

private boolean _hasLoadedOnce= false; // your boolean field

@Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
    super.setUserVisibleHint(true);


    if (this.isVisible()) {
        // we check that the fragment is becoming visible
        if (isFragmentVisible_ && !_hasLoadedOnce) {
            new NetCheck().execute();
            _hasLoadedOnce = true;
        }
    }
}
like image 166
Kjell Avatar answered Oct 19 '22 12:10

Kjell