how load fragment in ViewPager only when its selec

2019-01-18 04:35发布

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

    }

} 

5条回答
劳资没心,怎么记你
2楼-- · 2019-01-18 05:00

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-18 05:06

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;
        }
    }
}
查看更多
走好不送
4楼-- · 2019-01-18 05:07

Slightly modified version to fix potential NPE caused by some views not fully initialised

private boolean _hasLoadedOnce= false; // your boolean field

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


    if (this.isVisible()) {
        // we check that the fragment is becoming visible
        if (!isFragmentVisible_ && !_hasLoadedOnce) {
            new Handler().post(() -> {
                makeAsyncRequest();//do your asyn stuffs 
                _hasLoadedOnce = true;
            });
        }
    }
}
查看更多
太酷不给撩
5楼-- · 2019-01-18 05:18

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:

private boolean loadFragmentExecuted = false;

in the child fragments create a generic method called loadFragment and move all of the logic you added in onCreateView to that method:

public void loadFragment()
{
    if(!loadFragmentExecuted)
    {
        //Add your logic to manipulate the UI or load data etc...
        loadFragmentExecuted = true;
    }
}

in your pageview logic create the fragments dynamically like:

//add the fragment
String fragmentName = "com.something." + fragmentId;

//check if the class exists
try
{
    Class myFragmentClass = Class.forName(fragmentName);
    Fragment myFragment = (Fragment) myFragmentClass.newInstance();
    mFragments.add(myFragment);
}
catch (ClassNotFoundException e)
{
    e.printStackTrace();
}
catch (IllegalAccessException e)
{
    e.printStackTrace();
}
catch (InstantiationException e)
{
    e.printStackTrace();
}

then set your pager adapter and attach a tablayout with it:

//set our pager adapter that contains different fragments
mPagerAdapter = new BasePagerAdapter(mFragmentManager, mFragments);

//link the adapter to the viewpager
mViewPager.setAdapter(mPagerAdapter);

//cache fragments
int limit = (mPagerAdapter.getCount() > 0 ? mPagerAdapter.getCount() : 1);
mViewPager.setOffscreenPageLimit(limit);

//add the page listner to the viewPager and link it to the tabLayout
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));

//on tab selected select current viewpager item
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
    @Override
    public void onTabSelected(TabLayout.Tab tab)
    {
        mViewPager.setCurrentItem(tab.getPosition());

        //get fragment for the selected tab
        Fragment f = mPagerAdapter.getItem(tab.getPosition());

        //load the content of the fragment
        try
        {
            Class c = f.getClass();
            Method loadFragment = c.getMethod("loadFragment");
            loadFragment.invoke(f);
        }
        catch (IllegalAccessException e){}
        catch (InvocationTargetException e){}
        catch (NoSuchMethodException e){}
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab)
    {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab)
    {
    }
});
查看更多
【Aperson】
6楼-- · 2019-01-18 05:24

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:

private boolean _hasLoadedOnce= false; // your boolean field

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


    if (this.isVisible()) {
        // we check that the fragment is becoming visible
        if (!isFragmentVisible_ && !_hasLoadedOnce) {
            //run your async task here since the user has just focused on your fragment
            _hasLoadedOnce = true;
        }
    }
}

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.

查看更多
登录 后发表回答