从 Java 代码指定 DIP 维度的正确方法是什么? [英] What is the correct way to specify dimensions in DIP from Java code?

查看:14
本文介绍了从 Java 代码指定 DIP 维度的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现可以使用 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.密度 = 倾斜

pixels * DisplayMetrics.density = dip

Android 中是否有用于转换的实用函数?

Is there a utility function for the conversion somewhere in Android?

推荐答案

有一个名为 TypedValue.applyDimensions(int, float, 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_SPCOMPLEX_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.

我也遇到了同样的问题,通过翻代码发现了这个问题.

I encountered the same problem and found this through poking around the code.

这篇关于从 Java 代码指定 DIP 维度的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆