开发者

TabHost setCurrentTab only calls oncreate method for Activity in Tab once

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开发者_如何学JAVA 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.


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.


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)


another method you can call if use TabActivity.getCurrentActivity()


As pointed out by @Cristian, it's a matter of efficiency. but you can always use the onResume() method in your child activity instead.

@Override
protected void onResume() {
     super.onResume();               
     // do work 

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜