From Android 4.3 (API 18) and up you can use this code directly in your Fragment:
Kotlin
view?.viewTreeObserver?.addOnWindowFocusChangeListener { hasFocus -> /*do your stuff here*/ }
or define this extension in your project:
fun Fragment.addOnWindowFocusChangeListener(callback: (hasFocus: Boolean) -> Unit) =
view?.viewTreeObserver?.addOnWindowFocusChangeListener(callback)
then simply call
addOnWindowFocusChangeListener { hasFocus -> /*do your stuff here*/ }
anywhere in your fragment (just be careful that the root view is still not null at that time).
Note: don't forget to remove your listener when you're done (removeOnWindowFocusChangeListener() method)!
Java
getView().getViewTreeObserver().addOnWindowFocusChangeListener(hasFocus -> { /*do your stuff here*/ });
or without lambda:
getView().getViewTreeObserver().addOnWindowFocusChangeListener(new ViewTreeObserver.OnWindowFocusChangeListener() {
@Override
public void onWindowFocusChanged(final boolean hasFocus) {
// do your stuff here
}
});
Where you can get the non-null View instance in the onViewCreated() method or simply call getView() from anywhere after that.
Note: don't forget to remove your listener when you're done (removeOnWindowFocusChangeListener() method)!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…