Update current fragment in FragmentPagerAdapter

I have a viewPager with a tab indicator. ViewPager is installed in SetAdaper using the FragmentPagerAdapter.

I have little understanding of how the internal functions of the FragmentPagerAdapter work. I noticed that neighboring fragments are resuming (called OnResume), although the neighbor is not showing.

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

Ad banner update
I want the banner ad installed in the footer to be updated by scrolling left once or expanding once to the right. Neighboring fragments are not recreated (good). But onResume is already called, avoiding banner updates. The loadBannerAd method is in the OnResume () method.



How can I call the loadBannerAd () method only for the current fragment with the 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 onCreateView() } .... }; 

But there is a danger that the fragment has not yet been created. Controlling the creation or absence of a fragment in an Activity leads to its purity.

enter image description here

+6
source share
1 answer

You just 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 process what happens in onPageSelected(int index) .

+6
source

All Articles