问题
I have 10 tabs in my activity
. As soon as I open the activity the first fragment gets displayed but the method (AsyncTask) present in the next fragment gets called. And if I go to the next tab say 3rd tab then the method present in the 4th fragment
gets called and so on.
I don't understand this behavior. Please help!
回答1:
You must know how the viewPager
works populating the fragment
in the different positions
When you start on the position 0, then the fragment
on the position 0 and the one of the position 1 are created.
Then when you swipe to the position 1 the fragment
on the 2 position is created, so you have now the three fragments
created on the different positions (0,1,2..assuming you have only 3 pages on the viewPager
).
We swipe to the position 2, the last one, and the fragment
on the first position (0) get destroy, so we have now the fragments
on the positions 2 and 3.
This is how Fragment
LifeCycle Works
you can set mViewPager.setOffscreenPageLimit(2); // 2 is just an example
to limit it
If you want some code to execute when Fragment
become Visible to User add part of code in setUserVisibleHint
method
回答2:
By default it is viewpager.setOffscreenPageLimit(1)
, meaning View pager will by default load atleast 1 on the right and one on the left tab of current tab.
It is done so, mostly because there is a point when you slide viewpager, when certain area of both tabs is visible. For those smooth transitions preloading is required.
You cannot set it viewpager.setOffscreenPageLimit(0).
The only way out is to use this method setUserVisibleHint
add this to your fragment
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
}else{
// fragment is no longer visible
}
}
This will be called only when that particular tab is visible to user, so only then you can call all loading function.
check sample example
回答3:
Put your AsyncTask method inside this.
You can override setMenuVisibility like this:
@Override
public void setMenuVisibility(final boolean visible) {
if (visible) {
//execute AsyncTask method
}
super.setMenuVisibility(visible);
}
Happy coding!!
回答4:
Override below method and move your code for Aync task into this instead of onStart() or onCreateView.
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Load your data here or do network operations here
isFragmentLoaded = true;
}
}
来源:https://stackoverflow.com/questions/47053884/oncreateview-of-second-fragment-tab-is-called-while-on-the-first