2

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

4

1 回答 1

0

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

于 2013-05-09T23:43:53.360 回答