I can\'t update the content in ViewPager.
What is the correct usage of methods instantiateItem() and getItem() in FragmentPagerAdapter class?
I was using onl
After hours of frustration while trying all the above solutions to overcome this problem and also trying many solutions on other similar questions like this, this and this which all FAILED with me to solve this problem and to make the ViewPager
to destroy the old Fragment
and fill the pager
with the new Fragment
s. I have solved the problem as following:
1) Make the ViewPager
class to extends FragmentPagerAdapter
as following:
public class myPagerAdapter extends FragmentPagerAdapter {
2) Create an Item for the ViewPager
that store the title
and the fragment
as following:
public class PagerItem {
private String mTitle;
private Fragment mFragment;
public PagerItem(String mTitle, Fragment mFragment) {
this.mTitle = mTitle;
this.mFragment = mFragment;
}
public String getTitle() {
return mTitle;
}
public Fragment getFragment() {
return mFragment;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public void setFragment(Fragment mFragment) {
this.mFragment = mFragment;
}
}
3) Make the constructor of the ViewPager
take my FragmentManager
instance to store it in my class
as following:
private FragmentManager mFragmentManager;
private ArrayList mPagerItems;
public MyPagerAdapter(FragmentManager fragmentManager, ArrayList pagerItems) {
super(fragmentManager);
mFragmentManager = fragmentManager;
mPagerItems = pagerItems;
}
4) Create a method to re-set the adapter
data with the new data by deleting all the previous fragment
from the fragmentManager
itself directly to make the adapter
to set the new fragment
from the new list again as following:
public void setPagerItems(ArrayList pagerItems) {
if (mPagerItems != null)
for (int i = 0; i < mPagerItems.size(); i++) {
mFragmentManager.beginTransaction().remove(mPagerItems.get(i).getFragment()).commit();
}
mPagerItems = pagerItems;
}
5) From the container Activity
or Fragment
do not re-initialize the adapter with the new data. Set the new data through the method setPagerItems
with the new data as following:
ArrayList pagerItems = new ArrayList();
pagerItems.add(new PagerItem("Fragment1", new MyFragment1()));
pagerItems.add(new PagerItem("Fragment2", new MyFragment2()));
mPagerAdapter.setPagerItems(pagerItems);
mPagerAdapter.notifyDataSetChanged();
I hope it helps.