Bakus123
Bakus123

Reputation: 1399

ViewPager - onCreateView is not always called

I have a ViewPager with 10 pages. When I start the last (10th) page onCreateView() method of my fragment is called. When I swipe to the 9th page onCreateView() is called also. But when I back to the 10th page onCreateView() isn't called. What's wrong?

Upvotes: 18

Views: 12222

Answers (6)

Vinay
Vinay

Reputation: 1304

Try Extending FragmentStatePagerAdapter

Upvotes: 21

JamesC
JamesC

Reputation: 496

CommonWare's answer is the best and works like charm: simple add OnPageChangeListener to your ViewPager item, something like this:

ViewPager     viewPager    = null;
PagerAdapter  pagerAdapter = null;

//Some code come here...

pagerAdapter = new PagerAdapter(); //Or any class derived from it
viewPager    = (ViewPager)findViewById(R.id.container);//Connect it to XML
viewPager.setAdapter (mPagerAdapter); //Connect the two

//Next two lines are simply for fun...
//viewager.setPageTransformer(true, new DepthPageTransformer());
//viewPager.setPageTransformer(true, new PaymentZoomOutPageTransformer());

 viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }
        //This is the right place to connect the pages with a data struct!!!
        @Override
        public void onPageSelected(int position) {
            // Here you can connect the current displayed page with some data..
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

 //Here use the inflater to add views/pages
 //Don't forget to do:
 pagerAdapter.notifyDataSetChanged();
 //When you're done...

Upvotes: 1

Sergio Magoo Quintero
Sergio Magoo Quintero

Reputation: 249

I had the same problem, my solution was to assign again the adapter of the ViewPager instance, just like:

pager.setAdapter(adapter);

This causes a restart of the "mItems" property from the viewPager and removes the cache.

But I don't know if it's a safe solution

Upvotes: 2

Zvi
Zvi

Reputation: 2424

You can call the adapter getItem from onPageSelect, which is called also on swipes, and place your code inside the getItem, or even in the onPageSeelect itself.

Upvotes: 1

Fran b
Fran b

Reputation: 3036

That is because a FragmentPagerAdapter keeps in memory every fragment. Hence, when you visit the first time the fragment, onCreate will be invoked but the second time Android will looking for in memory, so it not need invoke onCreate.

If you need run the code in OnCreate every time fragment is displayed, you should move it to getItem(int id)

See offical documentation: http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html

Upvotes: 3

CommonsWare
CommonsWare

Reputation: 1006734

Nothing is wrong. The ViewPager already has the page, and so it does not need to create it.

Upvotes: 2

Related Questions