Why does calling getWidth() on a View in onResume() return 0?

后端 未结 2 813
感情败类
感情败类 2020-11-30 11:40

Everything I\'ve read says you can\'t call getWidth() or getHeight() on a View in a constructor, but I\'m calling them in onResu

2条回答
  •  醉梦人生
    2020-11-30 12:29

    A view still hasn't been drawn when onResume() is called, so its width and height are 0. You can "catch" when its size changes using OnGlobalLayoutListener():

    yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    
        @Override
        public void onGlobalLayout() {
    
            // Removing layout listener to avoid multiple calls
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
            else {
                yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
    
            populateData();
        }
    });
    

    For additional info take a look at Android get width returns 0.

提交回复
热议问题