问题
onCreateView
for my first fragment in the FragmentPagerAdapter is not very quick.
So, changing curent tab to the first has a delay.
How to disable recreate first Fragment in FragmentPagerAdapter on tab Selected?
private class TabsAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context context;
private ActionBar bar;
private final ViewPager viewPager;
private final ArrayList<TabInfo> tabs = new ArrayList<TabInfo>();
final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
context = activity;
bar = activity.getSupportActionBar();
viewPager = pager;
viewPager.setAdapter(this);
viewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
tabs.add(info);
bar.addTab(tab);
notifyDataSetChanged();
}
@Override
public int getCount() {
return tabs.size();
}
@Override
public Fragment getItem(int position) {
TabInfo info = tabs.get(position);
Fragment fragment = Fragment.instantiate(context, info.clss.getName(), info.args);
return fragment;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageScrollStateChanged(int state) {}
@Override
public void onPageSelected(int position) {
bar.setSelectedNavigationItem(position);
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i = 0; i < tabs.size(); i++) {
if (tabs.get(i) == tag)
viewPager.setCurrentItem(i);
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {}
}
回答1:
Right now i am stuck with the same problem.
when you are on a Tab:(n), only Tab:(n-1) and Tab:(n+1) will be alive in the memory, for memory usage optimization. Rest all Tabs will be destroyed, thats the reason why when you come back to the first Tab, its onCreateView is being called again.
Actually Tab:1's onCreateView will be called even if you click Tab:2 because its the neighbourhood Tab.
One solution i got is:
change the OffscreenPageLimit of the ViewPager. Its default value is 1
viewPager.setOffscreenPageLimit(total no of Tabs - 1);
This way all the Tabs will be alive even if its offScreen. But this is recommended only if you have decent no of Tabs(<=5)
If you have huge no.of Tabs, better use
FragmentStatePagerAdapter
来源:https://stackoverflow.com/questions/13422569/how-to-disable-recreation-of-the-first-fragment-in-fragmentpageradapter-on-tab-s