android屏幕适配

UI在不同的屏幕像素或大小中显示效果可能会不同

1、建议使用尽量使用线性布局和相对布局,基本上不会产生屏幕大小不适应的问题

2、设置控件宽高的时候使用单位dip(dp),是根据当前设备大小比例计算出来的

3、文字设置尽量使用sp单位

4、尽量不使用px设置大小

像素px和dip相互转换工具,实现两种单位的相互转换,达到适配屏幕的目的

工具类:DensityUtil

 1 package cn.itcast.mobilesafe.utils;
 2 
 3 import android.content.Context;
 4 
 5 public class DensityUtil {
 6     /** 
 7      * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
 8      */  
 9     public static int dip2px(Context context, float dpValue) {  
10         final float scale = context.getResources().getDisplayMetrics().density;  
11         return (int) (dpValue * scale + 0.5f);  
12     }  
13   
14     /** 
15      * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
16      */  
17     public static int px2dip(Context context, float pxValue) {  
18         final float scale = context.getResources().getDisplayMetrics().density;  
19         return (int) (pxValue / scale + 0.5f);  
20     }  
21 }

   转换方法:DensityUtil.dip2px(getApplicationContext(), 180)

原文地址:https://www.cnblogs.com/tagie/p/3161151.html