您可以通过附加/分离片段来实现此目的,每次未选择选项卡时在选项卡侦听器上分离当前片段并在 onTabSelected 方法上检查您之前是否创建过片段。
private Fragment mFragment;
private final String mTag;
private final Class<T> mClass;
public TabListener(String pTag, Class<T> pClass) {
mTag = pTag;
mClass = pClass;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if ( mFragment == null ) {
try {
mFragment = (Fragment)mClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ft.add(R.id.fragment_container,mFragment,mTag);
} else {
ft.attach(mFragment);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if ( mFragment != null ) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
//Nothing
}
然后你可以实例化你的听众,如
TabListener l = new TabListener<MyFragment>(tabTag, MyFragment.class)