Android Activity.onWindowFocusChanged doesn't get called from within TabHost

ε祈祈猫儿з 提交于 2019-12-10 22:57:04

问题


I'm struggling with the problem that the .onWindowFocusChanged() doesn't get called in my custom Activity class. My setup:

Two tabs (containing Activity_1 and Activity_2) in a TabHost, where the 2nd tab is selected by default:

tabHost.setCurrentTab(currentTabIndex);

In both Activities, I added the onWindowFocusChanged() override (because I need to preform calculations after the layout is done drawing):

@Override
public void onWindowFocusChanged(boolean hasFocus)
{
    super.onWindowFocusChanged(hasFocus);
}

The problem: when the 2nd tab is selected by default, and I click the 1st tab, the onWindowFocusChanged() never gets called within Activity_1 (associated with the 1st tab). Both Activities extend the normal Activity class.

Any clue on how to fix this would be greatly appreciated!


回答1:


If you need to wait until a specific View is draw and then make the calculations, you could use viewTreeObserver to listen the layout changes and make your calculations there. Use it like this:

ViewTreeObserver vto = mainLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
    // remove the listener so it won't get called again if the view layout changes
    mainLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    // add your calculations here
}}

EDIT:

Credit and thanks to Edison for the further details.

For those who want to support API < 16, you can do

if (Build.VERSION.SDK_INT >= 16) {     
    mainLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
} else { 
    mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
}


来源:https://stackoverflow.com/questions/11140120/android-activity-onwindowfocuschanged-doesnt-get-called-from-within-tabhost

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