问题
I am trying to implement FragmentTabs as illiustrated in http://developer.android.com/resources/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentTabs.html. Everything went well until i did this:
I started lots of different fragments from one tab like:
tab1-->fragment1--->fragment2--->fragment3
tab2
But when i switched to tab2 and again came back to tab1, I got fragment1 screen not fragment3(i.e. I have 3 fragments in first tab and while i am on 3rd fragment and I come again on first tab after switching to second tab, I am taken to 1st fragment not 3rd)..Can anyone tell what might be the prob?
@Override
public void onTabChanged(String tabId) {
TabInfo newTab = mTabs.get(tabId);
if (mLastTab != newTab) {
FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
if (mLastTab != null) {
if (mLastTab.fragment != null) {
ft.detach(mLastTab.fragment);
}
}
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(mActivity,
newTab.clss.getName(), newTab.args);
ft.add(mContainerId, newTab.fragment, newTab.tag);
} else {
ft.attach(newTab.fragment);
}
}
mLastTab = newTab;
ft.commit();
mActivity.getSupportFragmentManager().executePendingTransactions();
}
}
When i comment attach() and detatch(), I get this :

回答1:
Without more details it's tough to say what's wrong specificaly. However, I can say from personal experience that when I first had to implement fragment tabs, I went through a lot of lousy tutorials before finding something that worked. The tutorial that finally made sense for me is here: http://thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/
As a bonus, there's also some Github source code: https://github.com/mitchwongho/Andy/tree/master/Andy/src/com/andy/fragments/tabs
回答2:
Update:
I recommend you retain the original code for onTabChanged
and use addToBackStack
method for maintaining the traversal state of fragments. Call addToBackStack
when going from one fragment to next, like when add
ing or replace
ing fragments.
Also change the TabInfo.fragment
reference to reflect the transitions between fragments inside a tab.
Do not attach and detach every time tab is changed.
@Override
public void onTabChanged(String tabId) {
TabInfo newTab = mTabs.get(tabId);
if (mLastTab != newTab) {
FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
if (newTab != null) {
if (newTab.fragment == null) {
newTab.fragment = Fragment.instantiate(mActivity,
newTab.clss.getName(), newTab.args);
ft.add(mContainerId, newTab.fragment, newTab.tag);
} else {
ft.replace(mContainerId, newTab.fragment, newTab.tag);
}
}
mLastTab = newTab;
ft.commit();
mActivity.getSupportFragmentManager().executePendingTransactions();
}
}
来源:https://stackoverflow.com/questions/10600660/switching-between-fragmenttabs-giving-unexpected-results