1

I am trying to detect screen rotation for a view I have. I realized when there is a screen rotation, both View.OnLayoutChangeListener and ViewTreeObserver.OnGlobalLayoutListener are notified.

To determine which one I shall use for detecting screen rotation, I need to understand the circumstanced under which either of them are notified.

For View.OnLayoutChangeListener, it's clear from the documentation that it is notified when the view's bound changes.

However, the documentation for ViewTreeObserver.OnGlobalLayoutListener is unclear to me. So my question is that when exactly is ViewTreeObserver.OnGlobalLayoutListener be notified?

Having answered that question, then shall I use ViewTreeObserver.OnGlobalLayoutListener or View.OnLayoutChangeListener for detecting screen rotation?

user690421
  • 422
  • 1
  • 5
  • 15
  • 2
    If you're specifying "configChanges" in your Android manifest, you could just use the call to onConfigurationChanged in your Activity. – Submersed Apr 07 '15 at 22:05

1 Answers1

1

Submersed's comment is the correct answer. You should override onConfigurationChanged() to react to orientation changes.

Additionally, to prevent your Activity from restarting when the device is rotated, you should specify something like android:configChanges="orientation|keyboardHidden|screenSize" in your manifest.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        // landscape
    } else {
        // portrait
    }
}

See: prevent activity restarting when orientation changes

To answer your specific question, you might examine the source code.

Community
  • 1
  • 1
Peter
  • 4,021
  • 5
  • 37
  • 58
  • 1
    Thanks Peter for the answer. I was trying to handle screen-orientation change in a custom View, which doesn't have the onConfigurationChanged hook. I guess I shall expose a method on that view and let the Activity call it, – user690421 Apr 09 '15 at 19:13