Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 602
Daan Avatar asked Dec 20 '25 11:12

Daan


1 Answers

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); 
}
like image 172
Cata Avatar answered Dec 24 '25 09:12

Cata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!