这是一个注册监听视图树的观察者(observer),在视图树种全局事件改变时得到通知。这个全局事件不仅还包括整个树的布局,从绘画过程开始,触摸模式的改变等。最常见的用途时通过监听获知什么时候,视图的宽高值确定了,可以获取了,以便更改UI。
private final ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int width = -1;
int height = -1;
try {
width = getActivity().getWindow().getDecorView().getWidth();
height = getActivity().getWindow().getDecorView().getHeight();
} catch (Exception e) {
// called too early. so, just skip.
}
if (width != -1 && mGlobalLayoutWidth != width) {//只有当尺寸真正有了数值,即已经确定了,更新UI才有意义
mGlobalLayoutWidth = width;
updateUI();
} else if (height != -1 && mGlobalLayoutHeight != height) {
mGlobalLayoutHeight = height;
updateUI();
} } };mViewTreeObserver = getActivity().getWindow().getDecorView().getViewTreeObserver();
mViewTreeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener);android点滴之ViewTreeObserver,布布扣,bubuko.com
原文:http://blog.csdn.net/lskshz/article/details/25689423