Update the current fragment in FragmentPagerAdapter

13,781

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

Share:
13,781

Related videos on Youtube

Raymond Chenon
Author by

Raymond Chenon

This is me with Joel Spolsky in Berlin. http://betterapps.io/ portfolio http://www.linkedin.com/in/raychenon https://blog.raychenon.com https://github.com/raychenon

Updated on June 04, 2022

Comments

  • Raymond Chenon
    Raymond Chenon about 2 years

    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
    Raymond Chenon about 11 years
    thanks Warpzit , I knew about this method . Is there something more elegant ( I mean a method called within the fragment itself )
  • Warpzit
    Warpzit about 11 years
    @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...