Android getMeasuredHeight returns wrong values !

后端 未结 7 686
野的像风
野的像风 2020-12-02 20:13

I\'m trying to determine the real dimension in pixels of some UI elements !

Those elements are inflated from a .xml file and are initialized with dip width and height

7条回答
  •  Happy的楠姐
    2020-12-02 20:51

    view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
     @SuppressLint("NewApi")
     @SuppressWarnings("deprecation")
     @Override
      public void onGlobalLayout() {
       //now we can retrieve the width and height
       int width = view.getWidth();
       int height = view.getHeight();
    
    
       //this is an important step not to keep receiving callbacks:
       //we should remove this listener
       //I use the function to remove it based on the api level!
    
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN){
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }else{
            view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
      }
     });
    

    One should go with How to get width/height of a View

提交回复
热议问题