我将此侦听器用于选项卡,但是当屏幕旋转时,所有片段都会移动到初始状态:
public static class TabListener implements ActionBar.TabListener {
private final Activity mActivity;
/**
* HashMap with tab tag and tab frament
*/
private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();
/**
* Auxiliary class for storing tab info
*
*/
static final class TabInfo {
private final String mTag;
private final Class<? extends Fragment> mClass;
private Fragment mFragment;
TabInfo(String tag, Class<? extends Fragment> class_) {
mTag = tag;
mClass = class_;
}
}
public TabListener(Activity activity) {
mActivity = activity;
}
public void addTab(String tag, Class<? extends Fragment> class_) {
mTabs.put(tag, new TabInfo(tag, class_));
}
/* The following are each of the ActionBar.TabListener callbacks */
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
TabInfo tabInfo = mTabs.get(tab.getTag());
Fragment prevFragment = ((SherlockFragmentActivity) mActivity)
.getSupportFragmentManager().findFragmentByTag(
(String) tab.getTag());
if (prevFragment != null) {
tabInfo.mFragment = prevFragment;
}
if (tabInfo.mFragment == null) {
// If not, instantiate and add it to the activity
tabInfo.mFragment = Fragment.instantiate(mActivity,
tabInfo.mClass.getName());
ft.add(android.R.id.content, tabInfo.mFragment, tabInfo.mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(tabInfo.mFragment);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
TabInfo tabInfo = mTabs.get(tab.getTag());
if (tabInfo.mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(tabInfo.mFragment);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}