Reputation: 145
I'm developing an Android Application where I have a ViewPager in my MainActivity, consisting of 3 Fragments. The Problem is as follows, when I swipe to the 3rd fragment, and get back to the 1st one, onCreateView of fragment 1 is called which is what I really want, however, If I swipped to the 2nd fragment only, and returned to the 1st one, onCreateView is not called! I need to find a solution to this problem, I spent hours trying to find a solution but didn't know to solve it. Here's the code related to the ViewPager in my MainActivity
private void setupViewPager(final ViewPager viewPager) {
final ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new voting(), "ONE");
adapter.addFrag(new dashboard(), "TWO");
adapter.addFrag(new chats(), "THREE");
myAdapter=adapter;
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(0);
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<Fragment>();
private final List<String> mFragmentTitleList = new ArrayList<String>();
private ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
Log.i("getItem","getItem");
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
private void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
//added newly
@Override
public int getItemPosition(Object object){
return PagerAdapter.POSITION_NONE;
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
}
Upvotes: 1
Views: 1892
Reputation: 1763
This is intended behavior with a FragmentPagerAdapter
. If the fragment was already created and is still in memory, it is just reattached to the ViewPager. Hence, the reason why onCreateView(...)
isn't called a second time.
Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.
You're using a FragmentStatePagerAdapter
which is a subclass of FragmentPagerAdapter
, so it inherits this behavior.
Generally, it's not a good idea to recreate a view on every page change, as that is expensive and can lead to non smooth scrolling. If you had some logic in onCreateView(...)
that you want to run again on each fragment change, then I suggest looking into ViewPager.OnPageChangeListener
interface.
Upvotes: 2