The onResume () fragment is not called when using the FragmentPagerAdapter

I need my fragments to always call a specific function when they are an active fragment, so I put it in onResume (), but it is not called.

Fragment A

@Override public void onResume(){ super.onResume(); Log.d("clear state", " "+clear); if(clear == true) { restart(); clear = false; calculate(); } } 

I am using FragmentPagerAdapter with ViewPager to switch fragments

 public class ScoutingFragSingle extends FragmentPagerAdapter{ @Override public Fragment getItem(int index) { Bundle data = new Bundle(); switch(index){ case 0: TeamsFragment teamsFragment = new TeamsFragment(); data.putInt("current_page", index+1); teamsFragment.setArguments(data); return teamsFragment; case 1: data.putInt("current_page", index+1); data.putInt("matchId", matchNum); aFragment.setArguments(data); return aFragment; 

So, how would I make the fragments calling them onResume ()?

+4
source share
2 answers

I had the same problem as before.

Create a new interface and implement it as with Fragment s:

 public interface OnPageSelectedListener { void onPageSelected(); } 

In parent activity, we implement android.support.v4.view.ViewPager.OnPageChangeListener and call the Fragment method as follows:

 @Override public void onPageSelected(int i) { OnPageSelectedListener fragment = (OnPageSelectedListener ((PlaceListPagerAdapter)pager.getAdapter()).getFragment(i); fragment.onPageSelected(); } 

PS: The name of the new interface and its method are a bit confusing, so be careful or change it.

+5
source

Override Fragment.setUserVisibleHint . When setUserVisibleHint true calls the same logic that you use for onResume .

You can see when the FragmentPagerAdapter calls setUserVisibleHint in instantiateItem and setPrimaryItem . Applicable to android from 4.2.1 and support-v4.

+2
source

All Articles