目前,我有 2Fragments
,可通过以下方式切换ActionBar
's tab.
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab newTab = getSupportActionBar().newTab();
newTab.setText("history");
newTab.setTabListener(new TabListenerHistoryFragment>(this, "history",
HistoryFragment.class));
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
mFragment.setRetainInstance(true);
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
我第一次意识到我的Activity
(此活动持有2个片段)正在启动,Fragment
s 的方法将按以下顺序调用。
onCreate -> onCreateView -> onStart
当我进行Tab切换,然后Tab切换回同一个Fragment时,会再次调用以下方法。
onCreateView -> onStart
我只是希望在选项卡切换回来时保留相同的 GUI 视图状态。
- 我希望我的图表继续放大到之前的水平。
- 我希望我的图表水平滚动保持在之前的水平。
- 我希望我的列表继续滚动并保持在上一个级别。
- ...
我知道在 Tab 切换时可以使用以下方法保存/恢复简单变量
androidfragment-当另一个fragment被推到它上面时如何保存fragment中的视图状态 https://stackoverflow.com/questions/6787071/android-fragment-how-to-save-states-of-views-in-a-fragment-when-another-fragmen
但是,这不是我想要的,因为我的 GUI 状态很难在一大堆原始值中描述。
我尝试以下方法。当然它不会工作,因为我收到以下运行时错误。
public class HistoryFragment extends Fragment {
View view = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (this.view != null) {
return this.view;
}
this.view = inflater.inflate(R.layout.history_activity, container, false);
}
}
java.lang.IllegalStateException:指定的子级已经有父级。您必须首先对子级的父级调用removeView()。
我意识到下面的演示示例能够在选项卡切换时保留其片段 GUI 状态(例如,列表垂直滚动的位置)。但我想,也许是因为他们使用的是ListFragment?因为我没有发现他们执行任何特殊处理来保留 GUI 状态。
- com.example.android.apis.app.FragmentTabs
- com.example.android.apis.app.LoaderCursor.CursorLoaderListFragment
请问,如何避免在执行选项卡切换时重新创建相同的视图?