Android的指定像素单元(如SP,PX,DP)不使用XML [英] Android specifying pixel units (like sp, px, dp) without using XML

查看:225
本文介绍了Android的指定像素单元(如SP,PX,DP)不使用XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在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().

这篇关于Android的指定像素单元(如SP,PX,DP)不使用XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆