问题描述
我发现,有可能设置的使用DIP封装的XML布局我的界面元素尺寸作为下面的片段:
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"
但是,所有的Java接口采用整数作为参数,并没有办法来指定DIP封装尺寸。什么是计算这个正确的方法是什么?
But all Java interface takes integer as arguments and there is no way to specify dimensions in DIPs. What is the correct way to calculate this?
我想,我一定要使用 DisplayMetrics
类物业密度,但是这是一个正确的方法是什么?
I figured that I have to use property density of DisplayMetrics
class but is this a correct way?
我可以靠这个公式是总是正确的?
May I rely on this formula being always correct?
像素* DisplayMetrics.density = DIP
有没有效用函数的某处Android的转换?
Is there a utility function for the conversion somewhere in Android?
推荐答案
有内置现有的工具方法称为<$c$c>TypedValue.applyDimensions(int,浮动,DisplayMetrics) 才会这样。
There is an existing utility method built called TypedValue.applyDimensions(int, float, DisplayMetrics)
that does this.
下面是如何使用它:
// returns the number of pixels for 123.4dip
int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
(float) 123.4, getResources().getDisplayMetrics());
还有其他类型的列表,你可以用它包括使用 COMPLEX_UNIT_SP
, COMPLEX_UNIT_PT
页面中所有发现我挂上面。如果排除了(INT)类型转换,你会得到的浮点数。
There's a list of other types that you can use with it including COMPLEX_UNIT_SP
, COMPLEX_UNIT_PT
all found in the page I linked above. If you exclude the (int) typecast, you'll get the floating point number.
我遇到同样的问题,发现这个通过围绕code戳。
I encountered the same problem and found this through poking around the code.
这篇关于什么是从Java code指定DIP尺寸正确的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!