在方向更改后选择不在actionBar选项卡上显示的片段

时间:2013-05-09 22:37:57

标签: android android-fragments android-actionbar android-tabs

我无法通过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时我不会添加片段,但如果是这种情况,为什么所选片段会正确显示?此外,当我添加片段时,它们相互叠加......

1 个答案:

答案 0 :(得分:0)

它没有做任何事情因为onTabReselected被调用,你可以随意处理它,但这就是为什么当你选择标签时没有发生的事情