how to get the onWindowFocusChanged on Fragment?

Ben Luk picture Ben Luk · May 8, 2015 · Viewed 21.8k times · Source

I am using Android Sliding Menu using Navigation Drawer. I know that onWindowFocusChanged work on MainActivity. How can I check is it hasFocus on Fragment?

someone said that I can pass the hasFocus to fragment, but I dont know how to do this. Can anyone give me some sample code?

I want to run ↓ this on my fragment

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

    if (hasFocus) {
        //I need to do someing.
        method();
    }
}

Answer

Tomas picture Tomas · Sep 23, 2016

From Android 4.3 (API 18) 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.invoke(it) }

then simply call

addOnWindowFocusChangeListener { hasFocus -> /*do your stuff here*/ }

anywhere from your fragment (just be careful that the root view is still not null at that time).


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 object in the onViewCreated method or simply call view? / getView() from anywhere after that.