Skip to content Skip to sidebar Skip to footer

Android:how To Change Opened Tab Dynamically

I have an Android application which has four tabs (I use a main TabActivity with TabHost and TabSpecs). In one of my sub activity (activity opened in a tab), i need to open a tab n

Solution 1:

Found an easier (I think) answer:

  1. on the TabActivity declare a public, static and self variable and populate it on the onCreate method. F.e.:

    publicclassTheActivityextendsTabActivity {
        publicstatic TheActivity self;
        ...
        @OverridepublicvoidonCreate(Bundle savedInstanceState) {
            self=this;
    
  2. on any Activity running in a tab, when you want to change the one shown on your app. you can do this:

    TabHosttabHost= TheActivity.self.getTabHost();
    tabHost.setCurrentTab(0);
    

Worked ok for me, hope serves someone else!

Solution 2:

You have to use TabHost's "setCurrentTab(...)" for that. In one of my projects, I created a static method in the main Activity (the one with the TabHost), named "swtichToTab(int tab)". In my subactivites (those inside the tabs) could then just call "MainActivity.switchToTab()" to trigger switching.

It may not be the cleanest method, I'm sure you can achieve this using broadcast intents too.

Solution 3:

Solution 4:

You can use views instead of activities for the content of the tabs. This way, the code is simpler and doesn't use as much memory. Plus, you then can use the setCurrentTab(tabIndex) method to easily switch between views.

I have a simple tutorial here. It has a tab activity with a list and map view. When you you click on an item in the list, the activity dynamically goes to the map view (using the setCurrentTab(tabIndex) method). You can easily modify this to have a button switch views.

Post a Comment for "Android:how To Change Opened Tab Dynamically"