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

前端 未结 4 1264
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:29

    Using the display metrics density field, you can get a scaling factor to convert to/from dips. Use the Math.round method to convert from a float to an int without needing a cast or adding 0.5

    // Converting dips to pixels
    float dips = 20.0f;
    float scale = getContext().getResources().getDisplayMetrics().density;
    int pixels = Math.round(dips * scale);
    
    // Converting pixels to dips
    int pixels = 15;
    float scale = getContext().getResources().getDisplayMetrics().density;
    float dips = pixels / scale;
    

提交回复
热议问题