Get height and width of a layout programmatically

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

    try with this metods:

    int width = mView.getMeasuredWidth();
    
    int height = mView.getMeasuredHeight();
    

    Or

    int width = mTextView.getMeasuredWidth();
    
    int height = mTextView.getMeasuredHeight();
    
    0 讨论(0)
  • 2020-11-27 14:45

    I had same issue but didn't want to draw on screen before measuring so I used this method of measuring the view before trying to get the height and width.

    Example of use:

    layoutView(view);
    int height = view.getHeight();
    
    //...
    
    void layoutView(View view) {
        view.setDrawingCacheEnabled(true);
        int wrapContentSpec = 
            MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        view.measure(wrapContentSpec, wrapContentSpec);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    }
    
    0 讨论(0)
  • 2020-11-27 14:45

    try something like this code from this link

    ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
    if (viewTreeObserver.isAlive()) {
     viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
      view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
      viewWidth = view.getWidth();
      viewHeight = view.getHeight();
    }
     });
    }
    

    hope this helps.

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

    you can use coroutines as well, like this one :

    CoroutineScope(Dispatchers.Main).launch {
            delay(10)
            val width = view.width()
            val height= view.height()
            // do your job ....
        }
    
    0 讨论(0)
  • 2020-11-27 14:52

    As CapDroid say, you are trying to get the size before the view drawn, another possible solution could be to do a Post with a runnable on the View:

    mView.post(new Runnable() {
            @Override
            public void run() {
                int width = mView.getWidth();
                int height = mView.getHeight();
            }
    }
    
    0 讨论(0)
  • 2020-11-27 14:54

    I used DisplayMetrics to get the screen size and then i can assign the width/height to an element in %age

    It will be like this

    DisplayMetrics dmetrics = new DisplayMetrics();
    int widthPixels=dmetrics.widthPixels;
    int heightPixels=dmetrics.heightPixels;       
    
    //setting the height of the button 
    button_nextPuzzle.setMinHeight((int) ((heightPixels/3)*.30));
    

    Worked for me very well!!!

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