Android检测选中的选项卡并更改ActionBar

时间:2014-08-15 13:09:51

标签: android tabs

您好我有一个包含TabBar的ActionBar,并且在每个标签上我想根据选择的标签更改操作栏标题/图标。如何检测我所在的选项卡并运行if语句,例如if tab = tab1 then set actionbar title

继承我的活动

         ActionBar actionbar = getActionBar();
         actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
         getActionBar().setTitle("");
         getActionBar().setIcon(R.drawable.ab_logo);
         getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#000000")));
         actionbar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#eeeeee")));


         LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
         View tabView = inflater.inflate(R.layout.tab_3, null);


         ActionBar.Tab Tab1 = actionbar.newTab().setIcon(R.drawable.ic_tab_1);
         ActionBar.Tab Tab2 = actionbar.newTab().setIcon(R.drawable.ic_tab_2);
         ActionBar.Tab Tab3 = actionbar.newTab().setCustomView(tabView);
         ActionBar.Tab Tab4 = actionbar.newTab().setIcon(R.drawable.ic_tab_4);
         ActionBar.Tab Tab5 = actionbar.newTab().setIcon(R.drawable.ic_tab_5);



         Fragment Fragment1 = new Fragment1();
         Fragment Fragment2 = new Fragment2();
         Fragment Fragment3 = new Fragment3();
         Fragment Fragment4 = new Fragment4();
         Fragment Fragment3 = new Fragment5();


         Tab1.setTabListener(new MyTabsListener(Fragment1));
         Tab2.setTabListener(new MyTabsListener(Fragment2));
         Tab3.setTabListener(new MyTabsListener(Fragment3));
         Tab4.setTabListener(new MyTabsListener(Fragment4));
         Tab5.setTabListener(new MyTabsListener(Fragment5));

         actionbar.addTab(Tab1);
         actionbar.addTab(Tab2);
         actionbar.addTab(Tab3);
         actionbar.addTab(Tab4);
         actionbar.addTab(Tab5);

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }

}

继承我的TabListener类

public class TabListener implements ActionBar.TabListener {
    public Fragment fragment;
    public Context c;
    public ActionBar actionbar;

    public TabListener(Fragment fragment, Context con) {
        this.fragment = fragment;
        this.c = con;
    }   



    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {


    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.replace(R.id.fragment_container, fragment);

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {


    }

}