Java 如何在程序内将布局和文本大小设置为 DP?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3316431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:02:06  来源:igfitidea点击:

How do I set Layout and Text size to DP inside program?

javaandroidlayout

提问by RobGThai

Basically I have this inside XML, but I have to recreate it inside a code. How do I do it?

基本上我在 XML 中有这个,但我必须在代码中重新创建它。我该怎么做?

<EditText 
        android:layout_width="140dp"
        android:layout_height="20dp"
        android:background="@drawable/input_bg01"
        android:textSize="10dp"
        android:gravity="center"
        android:text="111-222-333     FOOO" />

I can use this to set text size, but what about the layout_width and height?

我可以用它来设置文本大小,但是 layout_width 和 height 呢?

edTxt.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);

Is there a way to tell the code to use DP unit instead of pixel? Or a conversion function to convert DP into pixel?

有没有办法告诉代码使用 DP 单位而不是像素?或者是将DP转换成像素的转换函数?

采纳答案by sven

Solved here.

在这里解决

Extract:

提炼:

DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
float dp = 20f;
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);

回答by Santosh

You can use:

您可以使用:

float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());

Now the value of pixelsis equivalent to 10dpat the device's current screen density.

现在 的值pixels等于10dp设备当前的屏幕密度。

The TypedValuecontains other similar methods that help in conversion.

的TypedValue包含其他类似的方法,在转换的帮助。

回答by Julian Horst

Just for completeness: Another solution (which I'd prefer) for the question is given here

只是为了完整性:这里给出了该问题的另一个解决方案(我更喜欢)

setTextSize(float)expects a scaled pixel value. So, setTextSize(10)would give you the desired result. However, getDimension()and getDimensionPixelSize()return the size in units of pixels.

setTextSize(float)期望缩放像素值。所以,setTextSize(10)会给你想要的结果。但是,getDimension()getDimensionPixelSize()以像素为单位返回大小。

So for your example it would be

所以对于你的例子,它会是

setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.edTxt_text_size));

where <dimen name="edtxt_text_size">10dp</dimen>is set in your dimens.xml file for example.

其中,<dimen name="edtxt_text_size">10dp</dimen>在例如你dimens.xml文件设置。