getWidth() and getHeight() always returning 0. Custom view

前端 未结 7 2051
悲哀的现实
悲哀的现实 2020-12-09 09:11

In a Fragment, I am inflating a Layout with multiple child View. I need to get the dimensions (width and height) of one of them which is a custom view.

Inside the

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 09:34

    You must wait until after the first measure and layout in order to get nonzero values for getWidth() and getHeight(). You can do this with a ViewTreeObserver.OnGlobalLayouListener

    public void onViewCreated(final View view, Bundle saved) {
        super.onViewCreated(view, saved);
        view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                  view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                  view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
    
                // get width and height of the view
            }
        });
    }
    

提交回复
热议问题