Android specifying pixel units (like sp, px, dp) without using XML

拥有回忆 提交于 2020-01-21 03:16:05

问题


Is it possible to specify the pixel unit in code. What I mean is, say I have a layout and I want the size to be 20dp, then is there any way to do so without writing in a layout xml


回答1:


In a view:

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

In an Activity, of course, you leave off the getContext().

To convert from scaled pixels (sp) to pixels, just use metrics.scaledDensity instead of metrics.density.

EDIT: As @Santosh's answer points out, you can do the same thing using the utility class TypedValue:

DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
float dp = 20f;
float fpixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
int pixels = Math.round(fpixels);

For sp, substitute TypedValue.COMPLEX_UNIT_SP for TypedValue.COMPLEX_UNIT_DIP.

Internally, applyDimension() does exactly the same calculation as my code above. Which version to use is a matter of your coding style.




回答2:


You can use

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

now, the value of pixels is equivalent to 20dp

The TypedValue contains other similar methods that help in conversion



来源:https://stackoverflow.com/questions/5012840/android-specifying-pixel-units-like-sp-px-dp-without-using-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!