TabHost setCurrentTab only calls oncreate method for Activity in Tab once

对着背影说爱祢 提交于 2019-12-12 11:08:24

问题


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.


回答1:


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.




回答2:


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)




回答3:


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




回答4:


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 

}


来源:https://stackoverflow.com/questions/3710222/tabhost-setcurrenttab-only-calls-oncreate-method-for-activity-in-tab-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!