很多人都想在activity載入完畢的同時處理一下事件,如彈出一個popWindow或者其他,但在onCreate方法中處理這個時間的話,程式會報錯:大意是activity還沒有載入完,不能處理彈窗事件,其實不光是彈窗,只要用到activity.this的事件,在activity載入完之前都不能處理,原因很明顯——popWindow或者是dialog的顯示都要依附在一個parent Activity上,所以在Activity載入完之間,他們都不能顯示。
不過萬幸的是android給開發人員提供了一個方法,可以解決這個問題,這個方法就是onWindowFocusChanged()
其說明如下:
Called when the current Window
of
the activity gains or loses focus. This is the best indicator of whether this activity is visible to the user. The default implementation clears the key tracking state, so should always be called.
Note that this provides information about global focus state, which is managed independently of activity lifecycles. As such, while focus changes will generally have some relation to lifecycle changes (an activity that is
stopped will not generally get window focus), you should not rely on any particular order between the callbacks here and those in the other lifecycle methods such as onResume()
.
As a general rule, however, a resumed activity will have window focus... unless it has displayed other dialogs or popups that take input focus, in which case the activity itself will not have focus when the other windows
have it. Likewise, the system may display system-level windows (such as the status bar notification panel or a system alert) which will temporarily take window input focus without pausing the foreground activity.
Java代碼
- @Override
- public void onWindowFocusChanged(boolean hasFocus)
- {
- if (hasFocus)
- {
- }
- }