I am working on Fragments,so here I have three fragments in My view pager
So here I am using onResume()
method in my first fragment, so when I swipe from one fragment to another and I came back to first fragment My onResume
Method is not working
So any one give the solutions guys
The fragment's
onResume()
or onPause()
will be called only when the Activities
onResume()
or onPause()
is called. They are tightly coupled to the Activity
. Check this and this .
Also it may get called few times when you are on fragment
screen. In your case since your viewpager
is inside Activity
, fragment onResume()
may not get called when you swipe to that fragment
.
This is due to the way ViewPager
keeps Fragment
s in memory. If the Fragment
is scrolled more than the offscreen page limit (set via .setOffscreenPageLimit()
), it should be removed from memory and reinstantiated when it's reloaded (which, IIRC, may not be guaranteed to be when it comes back onscreen).
To run fragment-specific code when a page is selected, you can try something like the following:
mPager.setOnPageChangeListener(new SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
final MyFragment fragment = mAdapter.getFragment(position);
fragment.myMethod();
}
}
I faced this problem myself.
Add a tabListener
to your viewpager first. In the onTabSelected
method, create an instance of your selected fragment and call onResume()
.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
mContent.setUserVisibleHint(false);
mContent.onPause();
mContent = mAdapter.getItem(tab.getPosition());
mContent.setUserVisibleHint(true);
mContent.onResume();
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
Here, mContent
is the currently selected fragment, and mAdapter
is the viewpager's adapter.
In fragment (with ViewPager) use setUserVisibleHint(boolean isVisibileToUser) instead onResume():
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
refresh();
} else {
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.