Update the current fragment in FragmentPagerAdapter

Raymond Chenon picture Raymond Chenon · Apr 18, 2013 · Viewed 13.8k times · Source

I have a viewPager with tab indicator. The ViewPager is setAdaper with a FragmentPagerAdapter.

I have little understanding how the internals of FragmentPagerAdapter work. I noticed that the neighbor fragments are resumed ( OnResume is called ) , even though the neighbor are not yet visible.

I put the update methods in OnResume thinking that once the fragment is current, it will be updated.

Ad banner refresh
I want the ad banner set in the footer to update when swiping to the left once or swipping once to the right . The neighbor fragments are not recreated ( good thing ). But onResume is already called avoiding the banner refresh. The method loadBannerAd is in OnResume() method.



How can I call the method loadBannerAd() only for the current fragment by a method inside the fragment ?

EDIT : I already know about mViewPager.setOnPageChangeListener() .

    OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
        // this method can be called before the fragment 's onCreateView()
        }

        ....
    };

But there is a danger when the fragment has not been created yet . Managing whether the fragment has been created or not in the Activty defeats the purepose of it.

enter image description here

Answer

Warpzit picture Warpzit · Apr 18, 2013

You simply use:

mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int index) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        })

Then you can handle what happens in onPageSelected(int index).