当前位置:   article > 正文

Android并以dp为单位以编程方式设置宽度和高度_红魔手机 调dp宽度

红魔手机 调dp宽度

本文翻译自:Android and setting width and height programmatically in dp units

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". 根据文档,宽度和高度的单位(上面均为65)是“像素”。 How do you force this to be device independent pixels, or "dp"? 你如何强制这是设备无关的像素,或“dp”?


#1楼

参考:https://stackoom.com/question/m372/Android并以dp为单位以编程方式设置宽度和高度


#2楼

I know this is an old question however I've found a much neater way of doing this conversion. 我知道这是一个老问题但是我发现了一种更简洁的方式来进行这种转换。

Java Java的

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

Kotlin 科特林

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

#3楼

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. 您似乎在编译时知道dp中的维度,因此您可以在资源中添加维度条目。 Then you can query the dimen entry and it will be automatically converted to pixels in this call: 然后你可以查询dimen条目,它将自动转换为此调用中的像素:

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

And your dimens.xml will have: 而您的dimens.xml将具有:

<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. 扩展这个想法,你可以简单地存储1dp或1sp的值作为维度条目并查询该值并将其用作乘数。 Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations. 使用此方法,您将使代码与数学内容隔离,并依赖库来执行计算。


#4楼

simplest way(and even works from api 1) that tested is: 测试的最简单方法(甚至可以从api 1开始):

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

From documentations: 来自文件:

Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. 检索特定资源ID的维度,以用作原始像素的大小。 This is the same as getDimension(int), except the returned value is converted to integer pixels for use as a size. 这与getDimension(int)相同,只是将返回的值转换为整数像素以用作大小。 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. 是的,它会使值四舍五入,但它并不是很糟糕(只是在hdpi和ldpi设备上的奇数值需要在ldpi不常见时添加一点值)我在xxhdpi设备中测试,将4dp转换为16(像素),这是真正。


#5楼

You'll have to convert it from dps to pixels using the display scale factor. 您必须使用显示比例因子将其从dps转换为像素。

  1. final float scale = getContext().getResources().getDisplayMetrics().density;
  2. int pixels = (int) (dps * scale + 0.5f);
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号