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:<
Add this to view pager to reload for next fragment:
viewPager.setCurrentItem()
Exactly like my APP doing...
For change ViewPagerAdapter, what I did is :
Clear all Fragments inside current adapter
Set current adapter to null
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~
I see that @RRTW way worked for some people but it did not do the trick for me (although it was close). Without commitNow()
instead of regular commit()
it would not work properly. I did something like that:
private fun changePagerAdapter(newAdapter: PagerAdapter) {
val transaction = supportFragmentManager.beginTransaction()
supportFragmentManager.fragments.forEach {
transaction.remove(it)
}
transaction.commitNow()
view_pager.adapter = newAdapter
}
You need to override public int getItemPosition (Object object)
in pager adapter. For every element in the viewpager, you need to return POSITION_UNCHANGED
(if it is still in the pager) or POSITION_NONE
(if it was removed). Otherwise the view pager won't know something has changed. I wouldn't recommend setting a new adapter, just clearing out the data in the old one.