Update Fragment from ViewPager
Solution 1:
Update Fragment from ViewPager
You need to implement getItemPosition(Object obj)
method.
This method is called when you call
notifyDataSetChanged()
on your ViewPagerAdaper
. Implicitly this method returns POSITION_UNCHANGED
value that means something like this:
"Fragment is where it should be so don't change anything."
So if you need to update Fragment you can do it with:
- Always return
POSITION_NONE
fromgetItemPosition()
method. It which means: "Fragment must be always recreated" - You can create some update() method that will update your Fragment(fragment will handle updates itself)
Example of second approach:
public interface Updateable {
public void update();
}
public class MyFragment extends Fragment implements Updateable {
...
public void update() {
// do your stuff
}
}
And in FragmentPagerAdapter you'll do something like this:
@Override
public int getItemPosition(Object object) {
MyFragment f = (MyFragment ) object;
if (f != null) {
f.update();
}
return super.getItemPosition(object);
}
And if you'll choose first approach it can looks like:
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Note: It's worth to think a about which approach you'll pick up.
Solution 2:
I faced problem some times so that in this case always avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.
It work for me. I hope it will work for you also.
Solution 3:
I implement a app demo following Sajmon's answer. Just for anyone else who search this question.
You can access source code on GitHub
Solution 4:
In your PagerAdapter override getItemPosition
@Override
public int getItemPosition(Object object) {
// POSITION_NONE makes it possible to reload the PagerAdapter
return POSITION_NONE;
}
After that add viewPager.getAdapter().notifyDataSetChanged(); this code like below
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
viewPager.getAdapter().notifyDataSetChanged();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
should work.