Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabHost setCurrentTab only calls oncreate method for Activity in Tab once

Tags:

android

tabs

I'm following the example here:

http://developer.android.com/resources/tutorials/views/hello-tabwidget.html

Everything works fine. The first time I click on each tab, the oncreate method for Activity bound to that particular tab is called. However, subsequent selections of the tab's do not call this oncreate method.

I need to be able to execute oncreate (or another method) on the Activity that is bound to each Tab, when that tab is selected. I know I can use a setOnTabChangedListener, but I am unsure how to get access to the Activity that is bound to the tab, so that I can call the oncreate (or another) method.

like image 851
Jason Avatar asked Sep 14 '10 15:09

Jason


2 Answers

It's a matter of efficiency... that's why your onCreate method is not being called twice or more times. The eaiser way to access your activity from your TabActivity through the OnTabChangedListener is this:

public class YourTabActivity extends TabActivity{
    public void onCreate(Bundle InSavedInstanceState) {
        super.onCreate(InSavedInstanceState);
        final TabHost tabHost = getTabHost();

        // blablabla

        tabHost.setOnTabChangedListener(new OnTabChangeListener() {
            public void onTabChanged(String tabId) {
                if( tabId.equals("the_id_of_your_tab") ){
                    NameOfThatActivity.self.theMethodYouWantToCall();
                }
            }
        });
    }
}

Then, on your child activity, you have something like:

public class NameOfThatActivity extends Activity{

    public static NameOfThatActivity self;

    // blah blah blah
    public onCreate(Bundle b){
        super.onCreate(b);
        self = this;
    }

    public void theMethodYouWantToCall(){
        // do what ever you want here
    }
}

It's not beauty, but it works fine.

like image 196
Cristian Avatar answered Nov 15 '22 09:11

Cristian


Look at the onStart method in the Activity class, I think you are wanting to override that instead of onCreate (or in addition to, typically you call setContentView only in onCreate)

like image 35
Hamy Avatar answered Nov 15 '22 09:11

Hamy