0

I'm using the following code to detect whether or not the keyboard is showing throughout the lifetime of an activity:

rootVTO = root.getViewTreeObserver();
    keyboardListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (root.getRootView().getHeight() - root.getHeight() > 150) {
                // Keyboard showing
                isKeyboardShowing = true;
            } else {
                // Keyboard not showing
                isKeyboardShowing = false;
            }

            refreshLayout();
        };
    };
    rootVTO.addOnGlobalLayoutListener(keyboardListener);

I tried to remove the listener in the onPause() method but get the message:

Caused by: java.lang.IllegalStateException: This ViewTreeObserver is not alive, call getViewTreeObserver()

Will there be a memory leak if I don't remove the listener? If so when should I remove it? Is it sufficient to just set the listener to null?

Tom McFarlin
  • 829
  • 1
  • 9
  • 24
  • Might [this](http://stackoverflow.com/questions/22972022/why-does-calling-getwidth-on-a-view-in-onresume-return-0/22972145#22972145) help? – Onik Dec 19 '14 at 23:14
  • I'm familiar with this thread. I need to keep the listener throughout the activity not just when it is being inflated. So, once the activity ends I need to know how to correctly deal with the listener. – Tom McFarlin Dec 19 '14 at 23:44

1 Answers1

1

You don't need to remove the reference after your Activity is destroyed -- the Views will no longer be used and will be garbage collected along with your listener. However, if you do need to remove it for some other reason, don't maintain a reference to the ViewTreeObserver -- grab the reference from the View when you need it. That is, keep a reference to root, and when you want to remove the listener, call root.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardListener). The ViewTreeObserver instance on the root View may be replaced, so you could have a stale reference.

Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274