Android的指定像素单元(如SP,PX,DP)不使用XML像素、单元、Android、SP

由网友(回忆只能回忆)分享简介:是否有可能在code指定的像素单元。我的意思是,说我有一个布局,我想的大小为20dp,那么有没有什么办法可以这样做没有写在布局XML Is it possible to specify the pixel unit in code. What I mean is, say I have a layout and...

是否有可能在code指定的像素单元。 我的意思是,说我有一个布局,我想的大小为20dp,那么有没有什么办法可以这样做没有写在布局XML

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

推荐答案

在一个观点:

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

在一个活动,当然,你离开关闭的getContext()

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

阅读全文

相关推荐

最新文章