您的位置:首页 > 移动开发 > Android开发

Android 获取dip数据的三种途径

2016-05-20 16:16 621 查看
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息