问题
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