Android getMeasuredHeight returns wrong values !

后端 未结 7 685
野的像风
野的像风 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条回答
  •  一向
    一向 (楼主)
    2020-12-02 20:48

    Ok ! Kind of Answering my own question here...But not completly

    1 - It seems that on some devices, The ImageView measuring do not provide with exact values. I've seen lots of reports on this happenning on Nexus and Galaxy devices for example.

    2 - A work around that I've come up with :

    Set the width and height of your ImageView to "wrap_content" inside xml code.

    Inflate the layout inside your code (generally in the UI initialization I suppose).

    LayoutInflater inflater     = (LayoutInflater) 
    _parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ViewGroup root      = (ViewGroup) inflater.inflate(R.layout.tl_frame, null);
    ImageView frame = (ImageView) root.findViewById(R.id.TlFrame);
    

    Calculate your own ratio for your image view, based on the typical Android calculation

    //ScreenDpi can be acquired by getWindowManager().getDefaultDisplay().getMetrics(metrics);
     pixelWidth = wantedDipSize * (ScreenDpi / 160)
    

    Use the calculated size to set your ImageView dynamycally inside your code

    frame.getLayoutParams().width = pixeWidth;
    

    And voila ! your ImageView has now the wanted Dip size ;)

提交回复
热议问题