ViewTreeObserver.OnGlobalLayoutListener 什么时候通知 Android
When is ViewTreeObserver.OnGlobalLayoutListener notified in Android
我正在尝试检测我拥有的视图的屏幕旋转。我意识到当屏幕旋转时,View.OnLayoutChangeListener 和 ViewTreeObserver.OnGlobalLayoutListener 都会收到通知。
为了确定我应该使用哪个来检测屏幕旋转,我需要了解通知它们中的任何一个的情况。
对于 View.OnLayoutChangeListener,从文档中可以清楚地看出,当视图的绑定更改时会收到通知。
但是,我不清楚 ViewTreeObserver.OnGlobalLayoutListener 的文档。所以我的问题是 ViewTreeObserver.OnGlobalLayoutListener 什么时候收到通知?
回答完这个问题,那我是用ViewTreeObserver.OnGlobalLayoutListener还是View.OnLayoutChangeListener检测屏幕旋转?
Submersed 的评论是正确答案。您应该覆盖 onConfigurationChanged()
以响应方向变化。
此外,为了防止您的 Activity
在设备旋转时重新启动,您应该在清单中指定类似 android:configChanges="orientation|keyboardHidden|screenSize"
的内容。
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// landscape
} else {
// portrait
}
}
参见:prevent activity restarting when orientation changes
要回答您的具体问题,您可以检查 the source code。
我正在尝试检测我拥有的视图的屏幕旋转。我意识到当屏幕旋转时,View.OnLayoutChangeListener 和 ViewTreeObserver.OnGlobalLayoutListener 都会收到通知。
为了确定我应该使用哪个来检测屏幕旋转,我需要了解通知它们中的任何一个的情况。
对于 View.OnLayoutChangeListener,从文档中可以清楚地看出,当视图的绑定更改时会收到通知。
但是,我不清楚 ViewTreeObserver.OnGlobalLayoutListener 的文档。所以我的问题是 ViewTreeObserver.OnGlobalLayoutListener 什么时候收到通知?
回答完这个问题,那我是用ViewTreeObserver.OnGlobalLayoutListener还是View.OnLayoutChangeListener检测屏幕旋转?
Submersed 的评论是正确答案。您应该覆盖 onConfigurationChanged()
以响应方向变化。
此外,为了防止您的 Activity
在设备旋转时重新启动,您应该在清单中指定类似 android:configChanges="orientation|keyboardHidden|screenSize"
的内容。
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// landscape
} else {
// portrait
}
}
参见:prevent activity restarting when orientation changes
要回答您的具体问题,您可以检查 the source code。