Get height and width of a layout programmatically

前端 未结 16 1476
别那么骄傲
别那么骄傲 2020-11-27 13:55

I have designed an layout in which LinearLayout has 2 children LinearLayout and FrameLayout and in each child I put different views.

16条回答
  •  不知归路
    2020-11-27 14:58

    The view itself, has it's own life cycle which is basically as follows:

    • Attached

    • Measured

    • Layout

    • Draw

    So, depending on when are you trying to get the width/height you might not see what you expect to see, for example, if you are doing it during onCreate, the view might not even been measured by that time, on the other hand if you do so during onClick method of a button, chances are that by far that view has been attached, measured, layout, and drawn, so, you will see the expected value, you should implement a ViewTreeObserver to make sure you are getting the values at the proper moment.

    LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
    ViewTreeObserver vto = layout.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    this.layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } 
            int width  = layout.getMeasuredWidth();
            int height = layout.getMeasuredHeight(); 
    
        } 
    });
    

提交回复
热议问题