Avoid using "px" as units; use "dp" instead

来源:互联网 发布:梦里花落知多少 阅读 编辑:程序博客网 时间:2024/05/17 01:35

今天在写程序的时候,使用px设置组件宽度,弹出Avoid using "px" as units; use "dp" instead的提示,并且编译不通过

dp是可以根据屏幕大小变化的,而px就不行,主要是Android不主张再使用固定的长度单位了,如果想把dp转换成px值,

那么使用如下的代码

public static int dpToPixels(Context context, float dp) {    final float scale = context.getResources().getDisplayMetrics().density;    return (int) (dp * scale + 0.5f);}