I have the following situation:
I have an Activity
that hosts a ViewPager
, and I have 4 Fragments
;
the ViewPager
Let me introduce my idea to you:
getCurrentItem()
ViewPager
getItem(int position)
FragmentPagerAdapter
Return the Fragment associated with a specified position. You can define an Interface holding the method for Network I/O like
public Interface INetworkOnFragment{
void handle(){
//...
}
}
And implement it on your fragments and handle their own business logic (Network calls).
In main Activity ,set ViewPager.OnPageChangeListener
on ViewPager object like here:
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
public void onPageScrollStateChanged(int state){
//donothing
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels){
//donothing
}
public void onPageSelected(int position){
INetworkOnFragment interface =(INetworkOnFragment) (pager.getAdapter().getItem(position));//get the current fragment and call handle method on it,dont need to care about whichever fragment it is .
interface.handle()
}
});
The most important is onPageSelected(int position)
,Inside the callback it get the current fragment and call handle method on it,dont need to care about whichever fragment it is .
Remember the handle method are called in Activity and not in fragments.All the Network calls are implemention of Interface,which make it easy to deal in Activity.