When you are creating your awesome Android app, you'll make use of the awesome Android libraries like listed on this page.
Sometimes you will face the problem that you want to add some behaviour to some component like a View.

I had the following problem: I was using Android material chips library, but I needed to do something when the user lost focus of the EditText. I have managed to get the EditText view instance by using View.findViewById(), but the library already had implemented OnFocusChangeListener. If I set my own OnFocusChangeListener implementation, then I will break the functionality of the library. So I had to find an alternative way to detect the focus/blur event.

You can do it with the following code:

ViewTreeObserver viewTreeObserver = getViewTreeObserver();
viewTreeObserver.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
    @Override
    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
        //oldFocus could be null
        if (oldFocus == null || !oldFocus.equals(myEditText)) {
            return;
        }
        doYourThing();
    }
});

 

Just don't forget to check if the oldFocus is null or not, or else you will get a NPE.