Search code examples
androidandroid-tabhostandroid-tabsandroid-tabactivity

Android how to add many menus for different tabs


I have many tabs like this:

TabHost th;
TabSpec spec;
th = (TabHost) findViewById(R.id.tabhost_template_two_tabs);
th.setup();
// all tab
spec = th.newTabSpec("All");
spec.setIndicator("All");
spec.setContent(R.id.tab_template_two_tabs_all);
th.addTab(spec);
// favorite tab
spec = th.newTabSpec("Favorite");
spec.setIndicator("Favorite");
spec.setContent(R.id.tab_template_two_tabs_favorite);
th.addTab(spec);

and for each tab i want to add a menu, how please?


Solution

  • Each Tabin the TabHost has a number starting from 0, so you have to know which tab you are in now by using int currentTab = th.getCurrentTab(); and then clear the previous menu by using menu.clear() then adding your new menu by using inflater.inflater(menuID, menu)

    @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            // TODO Auto-generated method stub
            MenuInflater inflater = getMenuInflater();
            int currentTab = th.getCurrentTab();
            Toast.makeText(getApplicationContext(), currentTab+"", Toast.LENGTH_SHORT);
            if (currentTab == 0){
                menu.clear();
                inflater.inflate(R.menu.first, menu);}
            else{
                menu.clear();
                inflater.inflate(R.menu.second, menu);}
            return super.onPrepareOptionsMenu(menu);
        }
    

    note:

    onCreateOptionsMenu will not help you in your case