Current, I have 2 Fragments that can switch through the ActionBar 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); } }
I understand that the first time my Activity (this activity contains 2 fragments) starts, Fragment s' methods will be called in the following sequence.
onCreate -> onCreateView -> onStart
When I switch Tab and then Tab switch back to the same fragment, the following methods will be called again.
onCreateView -> onStart
I just want to keep the GUI view state the same when Tab switches again.
- I want my schedule to continue to grow to the previous level.
- I want my horizontal scroll bar to stay the same.
- I want my list to continue scrolling to the previous level.
- ...
I know that I can save / restore simple variables using the following method when switching Tab
Android fragment. How to save view states in a fragment when another fragment is clicked on top of it.
But this is not what I want, since my GUI state is quite difficult to describe in general a bunch of primitive values.
I am trying the following approach. Of course, this will not work, as I get the following runtime error.
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: The specified child already has a parent. You must first call removeView () on the parent parent.
I understand that the following demo can save the state of its GUI fragment (for example, the position of the vertical scroll of the list) when switching Tab. But I think maybe it's because they use ListFragment? Since I do not believe that they perform any special processing to preserve the state of the GUI.
- com.example.android.apis.app.FragmentTabs
- com.example.android.apis.app.LoaderCursor.CursorLoaderListFragment
Can I find out how I can avoid re-creating the same view when switching to a tab?