android viewpager change adapter

Ste picture Ste · Oct 8, 2012 · Viewed 15.3k times · Source

I'm developing an app with a ViewPager for lateral scrolling tables, sometimes i need to change the adapter to load a different set of tables. I've tried to do the following:

mViewPager.setAdapter(new pagerAdapterPushed(getSupportFragmentManager()));
mViewPager.getAdapter().notifyDataSetChanged();
indicator.setViewPager(mViewPager);
indicator.invalidate();
mViewPager.invalidate();

but it always reload the previous data. Isn't it possibile to change the adapter of a ViewPager?

Answer

RRTW picture RRTW · Apr 11, 2013

Exactly like my APP doing...

For change ViewPagerAdapter, what I did is :

  1. Clear all Fragments inside current adapter

  2. Set current adapter to null

  3. Assign new adpater for ViewPager

    /* Clear all Fragments inside current adapter */
    public class MyPagerAdapter extends FragmentPagerAdapter
    {
      private ArrayList<Fragment> fragments = new ArrayList<Fragment>();
      //...some stuff
    
      public void clearAll() //Clear all page
      {
        for(int i = 0; i < fragments.size(); i ++)
        fragMan.beginTransaction().remove(fragments.get(i)).commit();
        fragments.clear();
      }
    }
    
    /* Set current adapter to null */
    Constants.VP.removeAllViews();
    Constants.VP.setAdapter(null);
    
    /* Assign new adpater for ViewPager */
    Constants.PAGER = new MyPagerAdapter(getSupportFragmentManager());
    Constants.VP.setAdapter(Constants.PAGER);
    

Hope it helps~