2

I have ViewPager with fragments. The adapter gets fragments from override method getItem ().

@Override
   public Fragment getItem(int position) {
   return new MyFragment();
}

I need the ViewPager to reload all its fragments at a certain event (for example press the button). I.e. all fragments (even the one that is now open and its neighbors) have been updated. How can this be realized?

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
Anasteisha
  • 21
  • 4

2 Answers2

2

In the adapter override getItemPosition like so:

public int getItemPosition(Object object) {
    return POSITION_NONE;
}

Then call adapter.notifyDataSetChanged() and the ViewPager will remove all views and reload them.

kalabalik
  • 3,792
  • 2
  • 21
  • 50
0

You can call the ViewPager to set the adapter again like this,

yourViewPager.setAdapter(yourAdapter);

But the problem is it will jump to the first element location(ie. to your first Fragment in the ViewPager). To avoid that you can have a Listener that listens to the current item(current fragment) of the ViewPager and store the current position in a variable. Now you we can use this variable to set the current item of the ViewPager after refreshing. Something like this,

yourViewPager.setAdapter(yourAdapter);
yourViewPager.setCurrentItem(currentPosition);

please correct me if my understanding is wrong.