Android 并以 dp 单位以编程方式设置宽度和高度

发布于 2024-10-21 10:52:33 字数 151 浏览 1 评论 0原文

我正在做:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

青瓷清茶倾城歌 2024-10-28 10:52:33

您必须使用显示比例因子将其从 dps 转换为像素。

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

You'll have to convert it from dps to pixels using the display scale factor.

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);
许一世地老天荒 2024-10-28 10:52:33

我知道这是一个老问题,但是我找到了一种更简洁的方法来进行这种转换。

Java

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, getResources().getDisplayMetrics());

Kotlin

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65f, resources.displayMetrics)

I know this is an old question however I've found a much neater way of doing this conversion.

Java

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, getResources().getDisplayMetrics());

Kotlin

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65f, resources.displayMetrics)
最好是你 2024-10-28 10:52:33

测试的最简单的方法(甚至可以从 api 1 开始工作)是:

getResources().getDimensionPixelSize(R.dimen.example_dimen);

来自文档:

检索特定资源 ID 的维度以用作大小
以原始像素为单位。这与 getDimension(int) 相同,除了
返回的值被转换为整数像素以用作尺寸。一个
大小转换涉及对基值进行舍入,并确保
非零基值的大小至少为一个像素。

是的,它对值进行四舍五入,但也不是很糟糕(只是 hdpi 和 ldpi 设备上的奇数值需要在 ldpi 不太常见时添加一点值)
我在将 4dp 转换为 16(像素)的 xxhdpi 设备中进行了测试,结果确实如此。

simplest way(and even works from api 1) that tested is:

getResources().getDimensionPixelSize(R.dimen.example_dimen);

From documentations:

Retrieve a dimensional for a particular resource ID for use as a size
in raw pixels. This is the same as getDimension(int), except the
returned value is converted to integer pixels for use as a size. A
size conversion involves rounding the base value, and ensuring that a
non-zero base value is at least one pixel in size.

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.

如梦初醒的夏天 2024-10-28 10:52:33

根据您的要求,还有替代解决方案。看来您在编译时知道 dp 中的尺寸,因此您可以在资源中添加尺寸条目。然后你可以查询 dimen 条目,它会在这个调用中自动转换为像素:

final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);

并且你的dimens.xml 将具有:

<dimen name="dimen_entry_in_dp">72dp</dimen>

扩展这个想法,你可以简单地将 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:

final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);

And your dimens.xml will have:

<dimen name="dimen_entry_in_dp">72dp</dimen>

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.

疯了 2024-10-28 10:52:33

基于 drspaceboo 的解决方案,借助 Kotlin,您可以使用扩展将 Float 更轻松地转换为 Dips。

fun Float.toDips() =
        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, resources.displayMetrics);

用法:

(65f).toDips()

Based on drspaceboo's solution, with Kotlin you can use an extension to convert Float to dips more easily.

fun Float.toDips() =
        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, resources.displayMetrics);

Usage:

(65f).toDips()
娇纵 2024-10-28 10:52:33

Kotlin 版本

val scale: Float = resources.displayMetrics.density
val resizedInDp = (stream.videoWidth * scale + 0.5f).toInt()

用法:-

val params: ViewGroup.LayoutParams = yourLayout!!.layoutParams
            val scale: Float = resources.displayMetrics.density
            params.width = (widthDp * scale + 0.5f).toInt() // dp to px
            params.height =
                (heightDp * scale + 0.5f).toInt() // setting height according to aspect ratio
            yourLayout!!.layoutParams = params

Kotlin Version

val scale: Float = resources.displayMetrics.density
val resizedInDp = (stream.videoWidth * scale + 0.5f).toInt()

Usage:-

val params: ViewGroup.LayoutParams = yourLayout!!.layoutParams
            val scale: Float = resources.displayMetrics.density
            params.width = (widthDp * scale + 0.5f).toInt() // dp to px
            params.height =
                (heightDp * scale + 0.5f).toInt() // setting height according to aspect ratio
            yourLayout!!.layoutParams = params
心如荒岛 2024-10-28 10:52:33

只需使用 androidx.annotation

@Dimension(unit = Dimension.DP)
private static final int strokeWidth = 1; 

Simply you can use androidx.annotation

@Dimension(unit = Dimension.DP)
private static final int strokeWidth = 1; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文