Activity lifecycle within a tabwidget

两盒软妹~` 提交于 2020-01-05 04:29:07

问题


I'm trying to notify my activity when the relevant tab is selected. Consider the follwoing situation:

MainActivity:

// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, HomeActivity.class);

// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("home").setIndicator("Home",
                  res.getDrawable(R.drawable.ic_tab_home))
              .setContent(intent);

tabHost.addTab(spec);

// Do the same for the other tabs
intent = new Intent().setClass(this, ProceduresActivity.class);
spec = tabHost.newTabSpec("procedures").setIndicator("Procedures",
                  res.getDrawable(R.drawable.ic_tab_checklist))
              .setContent(intent);
tabHost.addTab(spec);

Now, the first time my second tab is selected, the onCreate method of ProceduresActivity is called. What I want to be alble to do is, within ProceduresActivity, to be notified whenever tab 1 and tab 2 (mine) are selected. I tryed overriding onPause and onResume within ProceduresActivity however those are only called when the MainActivity is pasued / resumed and not when I switch tabs... So in other words I want ProceduresActivity to do something whenever the user selects second tab, and not only the first time. Can someone help me please? Thanks, Luca.


回答1:


Hmmm. This seems like it might be a little difficult (I'm not even sure it's possible) to achieve. There are two ways I can see that you could achieve the same results.

The first way is by have the first tab refresh it's data/information when the user goes back to it. This can be done in the onResume() and by adding a flag to it. Pretty simple.

If you need your activity to do something that will take some time, you can make an ActivityGroup. It's basically a controller for multiple activities. It starts them all at the same time and just chooses which one is shown at once. This means that (in your case) both activities would be running, but only one would be shown. When you want the first tab to do something while the user is using the second tab, you go to the ActivityGroup (which is like a controller) and tell it to do whatever you want with the first tab.

The only problem I see with the ActivityGroup route is binding it to your tabs, but there are many workarounds for this.




回答2:


Maybe this can help you, i use this to perform an action when the tabs change. But maybe you can alter it to do a specific action with every tab?

getTabHost().setOnTabChangedListener(new OnTabChangeListener() {
            public void onTabChanged(String tabId) {
                //TODO, action to be performed
            }
       }
});


来源:https://stackoverflow.com/questions/5819192/activity-lifecycle-within-a-tabwidget

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