how to get the onWindowFocusChanged on Fragment?

2019-01-22 21:04发布

问题:

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();
    }
}

回答1:

You can either create an interface and all your fragments implement this interface, and inside your onWindowFocusChanged you get the current fragment and pass call the method provided by the interface.

A sample interface for the fragments could be:

public interface IOnFocusListenable {
   public void onWindowFocusChanged(boolean hasFocus);
}

Your fragments have to implement this interface:

public class MyFragment implements IOnFocusListenable {
    ....
    public void onWindowFocusChanged(boolean hasFocus) {
        ...
    }
}

And in the onWindowFocusChanged of your Activity you can then do the following:

public class MyActivity extends AppCompatActivity {
   @Override
   public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        if(currentFragment instanceof IOnFocusListenable) {
            ((IOnFocusListenable) currentFragment).onWindowFocusChanged(hasFocus);
        }
    }
}

Or you create a listener and the active fragment is added to the listener. So if the fragment is made visible you subscribe to this listener, and everytime the onWindowFocusChangedevent is called you call this listener.

This approach is very similar to the above with the difference that there is a list of IOnFocusListenable's and those are triggered in the activities onWindowFocusChanged method



回答2:

From API 18 you can use this code directly in your Fragment:

view.getViewTreeObserver().addOnWindowFocusChangeListener(new ViewTreeObserver.OnWindowFocusChangeListener() {
    @Override
    public void onWindowFocusChanged(final boolean hasFocus) {
        // do your stuff here
    }
});

or more simply with lambda:

view.getViewTreeObserver().addOnWindowFocusChangeListener(hasFocus -> { /*do your stuff here*/ });

Where you can get the view in onViewCreated or simply call getView() from everywhere.