仅在选中时如何在 ViewPager 中加载片段

我在 Viewpager 中使用了 3 个 Fragments,问题是我在 Asynctask 和加载器中加载大数据.在像 HTC one 这样的设备上,它工作得很好,但是,在低端设备上,它需要很多时间.这主要是因为当我实现 pagerAdapter 时,我将 Fragments 放在了一个 ArrayList 中,这会在加载主 Activity 时强制 Fragments 实例化.我需要的是它只是加载"第一个片段(主),当用户 Swype 时,加载另一个片段.它有什么方法可以实现这一目标?这是我的页面适配器

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

    }

} 

推荐答案

Sun 的上述方法对我不起作用(也许对你有用),但我想我也会分享我对他方法的编辑.顺便说一句Sun,很好的方法!

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

相关文章