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

前端 未结 7 2053
悲哀的现实
悲哀的现实 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:39

    My preferred method is to add an OnLayoutChangeListener to the view that you want to track itself

    CustomView customView = ...
    
    customView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            // Make changes
        }
    });
    

    You can remove the listener in the callback if you only want the initial layout.

提交回复
热议问题