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?
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.