Get height and width of a layout programmatically

前端 未结 16 1310
别那么骄傲
别那么骄傲 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:56

    I think you are getting Height and Width in OnCreate() method that's why you getting always 0 values because at that time your view still not created.

    Try to get height and width on some button click or else..

    0 讨论(0)
  • 2020-11-27 14:57

    If you get -1 or -2 it could also be the numeric value of LayoutParams.WRAP_CONTENT (-2) or LayoutParams.MATCH_PARENT (-1).

    0 讨论(0)
  • 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(); 
    
        } 
    });
    
    0 讨论(0)
  • 2020-11-27 15:00

    The first snippet is correct, but you need to call it after onMeasure() gets executed. Otherwise the size is not yet measured for the view.

    0 讨论(0)
提交回复
热议问题