5

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

Raymond Chenon
  • 11,482
  • 15
  • 77
  • 110

1 Answers1

6

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).

Warpzit
  • 27,966
  • 19
  • 103
  • 155
  • thanks Warpzit , I knew about this method . Is there something more elegant ( I mean a method called within the fragment itself ) – Raymond Chenon Apr 18 '13 at 11:59
  • @raychenon no, I've searched and tryed everything but this is actually quite elegant. You can call a method in the fragment whenever onPageSelected is called if that is more to your preferences... – Warpzit Apr 18 '13 at 12:24