Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

android - how to get the onWindowFocusChanged on Fragment?

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...