可以定义一个工具类,用来获取系统的转化比值,然后需要使用时调用即可。具体代码如下:

/** * dp、sp转化工具 * * @author h55l5 * */public class DisplayUtil {    /** * 将px转化为dip,保证尺寸大小不变 * * @param context * @param pxValue * @return dp值 */    public static int px2dip(Context context, float pxValue) {        return (int) (pxValue / getScale(context) + 0.5f);    }    /** * 将dip值转化为对应的px值 * * @param context * @param dipValue * @return px值 */    public static int dip2px(Context context, float dipValue) {        return (int) (dipValue * getScale(context) + 0.5f);    }    /** * 将对应的px值转化为sp值 * * @param context * @param pxValue * @return 转化后的sp值 */    public static int px2sp(Context context, float pxValue) {        return (int) (pxValue / getFontScale(context) + 0.5f);    }    /** * 将对应的sp值转化为px值 * * @param context * @param spValue * @return 转化好的px值 */    public static int sp2px(Context context, float spValue) {        return (int) (spValue * getFontScale(context) + 0.5f);    }    /** * 获取系统的转化比例 * * @param context * @return */    private static float getScale(Context context) {        return context.getResources().getDisplayMetrics().density;    }    /** * 获取系统的转化比例 * * @param context * @return */    private static float getFontScale(Context context) {        return context.getResources().getDisplayMetrics().scaledDensity;    }}

还可以通过系统的方法来进行相关的转化,具体代码如下:

public class DisplayUtil {    public static int dp2px(Context context, int dp) {        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,                context.getResources().getDisplayMetrics());    }    public static int sp2px(Context context, int sp) {        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,                context.getResources().getDisplayMetrics());    }}

更多相关文章

  1. android Notification 的使用!!!
  2. Android(安卓)Tint使用
  3. Android——常用的系统服务
  4. Android(安卓)系统剪贴板的使用 - 复制、获取和清空
  5. Android系统架构介绍
  6. 【Tech-Android-View】Android中可以使用的网络音乐资源(榜单 歌
  7. 安卓模拟器Android(安卓)SDK Manager 无法获取SDK列表的解决办法
  8. Android使用criteria选择合适的地理位置服务实现方法
  9. Android(安卓)系统提供媒体库 URI 与 数据库的对应关系

随机推荐

  1. Android(安卓)的网络编程(14)-ttpClient
  2. android里面自定义RadioButton、CheckBox
  3. C语言的函数递归(下)
  4. Android(安卓)电子罗盘开发
  5. Android中BuildConfig类的那些事
  6. Android开发 常用控件罕见特殊属性集锦
  7. Activity与Service是否处于同一进程
  8. android照相功能介绍
  9. Android activity的DecorView的层次结构
  10. 读取local.properties文件