Reputation: 730
When I click the item in NavigationView, the UI replace the fragment in viewpager with other new fragment by call the following "setUpTab" method. The core codes is :
public void setUpTab(int id){
adapter.clear();
switch (id){
case R.id.nav_home:
adapter.addFragment(new EventFragment(),"Events");
adapter.addFragment(new OwnRepoFragment(),"Repository");
adapter.addFragment(new ContributeRepoFragment(),"Contribute");
break;
case R.id.nav_friends:
adapter.addFragment(new FollowerFragment(),"Follower");
adapter.addFragment(new FollowingFragment(),"Following");
break;
case R.id.nav_gist:
break;
case R.id.nav_setting:
break;
case R.id.nav_about:
break;
}
adapter.notifyDataSetChanged();
tab.setupWithViewPager(viewpager);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
public void clear(){
mFragments.clear();;
mFragmentTitles.clear();;
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
I want to load data when a fragment is insert into the viewpager again(The insertion happens when i call "adapter.addFragment()"). And I start the data-loading Thread in the life cycle method.But it seems that the life Cycle Methods(onCreate,onResume) are not always called.So I fail to get the chance to start the data-loading Thread.
How can I replace the fragment in viewpager and make the fragment go through the normal life cycle methods:onCreate,onCreateView,onResume ?
Upvotes: 1
Views: 1607
Reputation: 730
Finally,I fix it.
Use FragmentStatePagerAdapter instead of FragmentPagerAdapter
Implement getItemPosition like this:
@Override
public int getItemPosition(Object object){
return PagerAdapter.POSITION_NONE;
}
Call the Viewpager's setOffscreenPageLimit(int i) to save state.
Upvotes: 3
Reputation: 3670
Put the data-loading thread into onCreateView instead of onCreate.
Upvotes: 0