Android获取View组件宽度以及ViewTreeObserver(2)

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);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/c58ee9b0ef256c95f615c5bd861c2e19.html