What is the correct way to specify dimensions in DIP from Java code?

前端 未结 4 1269
Happy的楠姐
Happy的楠姐 2020-11-28 01:45

I found that it is possible to set dimensions of my interface elements in XML layouts using DIPs as in following fragment:

android:layout_width=\"10dip\"
         


        
4条回答
  •  孤城傲影
    2020-11-28 02:28

    That is the correct formula there. Although DisplayMetrics.density is not a static member, so, according to the same document you alluded to, correct usage is:

    // Maybe store this in a static field?
    final float SCALE = getContext().getResources().getDisplayMetrics().density;
    
    // Convert dips to pixels
    float valueDips = 16.0f;
    int valuePixels = (int)(valueDips * SCALE + 0.5f); // 0.5f for rounding
    

提交回复
热议问题