我無法使用ActionBar獲得片段的正常工作 - 當我更改Tab時片段正確切換。但是,當我旋轉手機,然後記得片段正確顯示(取決於所選內容),但我無法切換到另一個選項卡。沒有錯誤,沒有什麼,我不知道如何檢查什麼是錯的片段沒有顯示在actionBar選項卡上方向更改後選擇
MapHandlerFragment mMapHandler;
VehiclesFragment mVehiclesFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar ab = getSupportActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ab.setDisplayShowTitleEnabled(false);
ab.setDisplayShowHomeEnabled(false);
FragmentManager fm = getSupportFragmentManager();
mMapHandler = new MapHandlerFragment();
mVehiclesFragment = new VehiclesFragment();
if (savedInstanceState == null) {
fm.beginTransaction()
.add(android.R.id.content, mVehiclesFragment)
.add(android.R.id.content, mMapHandler)
.commit();
} else {
fm.beginTransaction()
.hide(mMapHandler)
.hide(mVehiclesFragment)
.commit();
}
Tab vehiclesTab = ab.newTab().setText("Pojazdy").setTag(FRAGMENT_VEHICLES)
.setTabListener(new MyTabsListener(mVehiclesFragment));
ab.addTab(vehiclesTab);
Tab mapTab = ab.newTab().setText("Mapa").setTag(FRAGMENT_MAP)
.setTabListener(new MyTabsListener(mMapHandler));
ab.addTab(mapTab);
if (savedInstanceState == null) {
ab.selectTab(mapTab);
} else {
String selected = savedInstanceState.getString(SELECTED_TAB);
if (selected == FRAGMENT_VEHICLES) {
ab.selectTab(vehiclesTab);
} else if (selected == FRAGMENT_MAP) {
ab.selectTab(mapTab);
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SELECTED_TAB, mSelectedTab);
}
protected class MyTabsListener implements ActionBar.TabListener {
private Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.show(fragment);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.hide(fragment);
}
}
}
我知道我不加整理碎片時savedInstanceState
不是null
,但如果這會是這樣的,爲什麼選定的片段顯示正確?此外,當我添加了片段,它們彼此疊加...
你是否檢查過你的'onTabReselected'是否被調用,我敢打賭,因爲沒有任何內容可以處理它 – tyczj 2013-05-09 23:07:06
@tyczj是的,它被調用,但是我應該放在那裏? – wasyl 2013-05-09 23:16:01
做任何你想要的應用程序時,選項卡被重新選擇 – tyczj 2013-05-09 23:19:43