28

How to use TabHost.OnTabChangeListener in android?

give me some example code... :(

thanks

Praveen
  • 90,477
  • 74
  • 177
  • 219

3 Answers3

76

why it would be my pleasure to help you good sir:

myTabHost.setOnTabChangedListener(new OnTabChangeListener(){
@Override
public void onTabChanged(String tabId) {
    if(TAB_1_TAG.equals(tabId)) {
        //destroy earth
    }
    if(TAB_2_TAG.equals(tabId)) {
        //destroy mars
    }
}});

Where TAB_1_TAG is the tag provided to the newTabSpec method when creating the tab.

vahidg
  • 3,953
  • 2
  • 22
  • 30
pgsandstrom
  • 14,361
  • 13
  • 70
  • 104
  • 7
    Thanks for the help, and I LOL'd so hard on // destroy earth and // destroy mars – Naskov Mar 28 '13 at 12:50
  • @pgsandstrom first of all, thanks a milion! there is so little on TabHost methods online at all. this really saved me. my only confusion is why the method call is `setOnTabChangedListener`, but it instantiates as `OnTabChangeListener()`. there is no "d" in the instantiation! hmm ;) – Azurespot Apr 29 '14 at 06:55
7

I think in many cases it makes sense to make your TabActivity the listener:

public class MyTabActivity extends TabActivity implements OnTabChangeListener {

    private TabHost tabHost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* Your onCreate code here */

        tabHost.setOnTabChangedListener(this);
    }

    /* ... */

    @Override
    public void onTabChanged(String tabId) {
        /* Your code to handle tab changes */
    }
}
jake_hetfield
  • 3,388
  • 1
  • 23
  • 30
0

You can use OnTabSelectedListener, here is an example.

  tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            switch (tab.getText().toString()) {
                case "yourTabTitle":
                    //todo your code
                    break;
            }
        }
        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            switch (tab.getText().toString()) {
                case "yourTabTitle":
                    //todo your code
                    break;
            }
        }
        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            switch (tab.getText().toString()) {
                case "yourTabTitle":
                    //todo your code
                    break;
            }
        }
    });
stevyhacker
  • 1,847
  • 2
  • 23
  • 31