1.第一种就是写个工具类UITools,获取手机的密度,然后根据公式转换
代码:

public static int px2dip(Context context, float px) {
float density = context.getResources().getDisplayMetrics().density;
return (int) (px * density + 0.5f);
}

2.第二种使用TypedValue里的applyDimension转换
代码:

int width= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,  
width, getResources().getDisplayMetrics());

3.第三种就是写配置文件dimens.xml
定义

<resources>
<dimen name="width">16dp</dimen>
</resources>

代码:

int width = context.getResources().getDimension(R.dimen.width)