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();
} } };
2、一般在onCreate或onCreateView中注册监听器
mViewTreeObserver = getActivity().getWindow().getDecorView().getViewTreeObserver();
mViewTreeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener);