我将这个监听器用于制表符但是当屏幕旋转时,所有碎片都会移动到初始状态:
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.
}
}
答案 0 :(得分:3)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
CustomFragment fragment;
if (savedInstanceState != null) {
fragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag("customtag");
} else {
fragment = new CustomFragment();
getSupportFragmentManager().beginTransaction().add(R.id.container, fragment, "customtag").commit();
}
...
}
尝试这一定会对你有所帮助。
答案 1 :(得分:0)
在片段中调用setRetainInstance(true)
。这将在屏幕旋转后保持状态。但请注意片段生命周期中的更改,请参阅Docs。