Android 并以 dp 单位以编程方式设置宽度和高度
我正在做:
button.setLayoutParams(new GridView.LayoutParams(65, 65));
根据文档,宽度和高度的单位(上面都是 65)是“像素”。如何强制其成为与设备无关的像素或“dp”?
I'm doing:
button.setLayoutParams(new GridView.LayoutParams(65, 65));
According to the docs the units for the width and height (both 65 in the above) are "pixels". How do you force this to be device independent pixels, or "dp"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您必须使用显示比例因子将其从 dps 转换为像素。
You'll have to convert it from dps to pixels using the display scale factor.
我知道这是一个老问题,但是我找到了一种更简洁的方法来进行这种转换。
Java
Kotlin
I know this is an old question however I've found a much neater way of doing this conversion.
Java
Kotlin
测试的最简单的方法(甚至可以从 api 1 开始工作)是:
来自文档:
是的,它对值进行四舍五入,但也不是很糟糕(只是 hdpi 和 ldpi 设备上的奇数值需要在 ldpi 不太常见时添加一点值)
我在将 4dp 转换为 16(像素)的 xxhdpi 设备中进行了测试,结果确实如此。
simplest way(and even works from api 1) that tested is:
From documentations:
Yes it rounding the value but it's not very bad(just in odd values on hdpi and ldpi devices need to add a little value when ldpi is not very common)
I tested in a xxhdpi device that converts 4dp to 16(pixels) and that is true.
根据您的要求,还有替代解决方案。看来您在编译时知道 dp 中的尺寸,因此您可以在资源中添加尺寸条目。然后你可以查询 dimen 条目,它会在这个调用中自动转换为像素:
并且你的dimens.xml 将具有:
扩展这个想法,你可以简单地将 1dp 或 1sp 的值存储为 dimen 条目并查询该值和将其用作乘数。使用这种方法,您可以将代码与数学内容隔离开来,并依靠库来执行计算。
Looking at your requirement, there is alternate solution as well. It seems you know the dimensions in dp at compile time, so you can add a dimen entry in the resources. Then you can query the dimen entry and it will be automatically converted to pixels in this call:
And your dimens.xml will have:
Extending this idea, you can simply store the value of 1dp or 1sp as a dimen entry and query the value and use it as a multiplier. Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations.
基于 drspaceboo 的解决方案,借助 Kotlin,您可以使用扩展将
Float
更轻松地转换为 Dips。用法:
Based on drspaceboo's solution, with Kotlin you can use an extension to convert
Float
to dips more easily.Usage:
Kotlin 版本
用法:-
Kotlin Version
Usage:-
只需使用
androidx.annotation
Simply you can use
androidx.annotation