How to programmatically switch tabs using buttonclick in Android

user552797 picture user552797 · Dec 23, 2010 · Viewed 38k times · Source

I have been struggling with this for a few days now. I'm trying to switch tabs programmatically upon a button click. My program works flawlessly if I just use the tabs to change activities, but wiring an onClick method with setCurrentTab results in an error. This is the method that will not work. It's a pretty basic and straightforward function but I haven't seen much documentation or examples of people attempting to wire a buttonclick with switching tabs. Thanks.

ImageButton next = (ImageButton) findViewById(R.id.ButtonAsk);
 next.setOnClickListener(new View.OnClickListener() 
         {         
  public void onClick(View view)  
             {

                TabHost tabHost =  (TabHost) findViewById(android.R.id.tabhost);
              tabHost.setCurrentTab(2);                
             }
         });

See the edit history for the error log.

Answer

SMBiggs picture SMBiggs · Nov 22, 2012

Here's a code example that you can put inside your onClick(). It's as Mark and Kevin described.

    TabActivity tabs = (TabActivity) getParent();
    tabs.getTabHost().setCurrentTab(2);

I've used this code tidbit numerous times. Hope this clarifies.