GitHub地址:https://github.com/raul-lsj/ScreenDensityUtils
参考今日头条技术团队:https://mp.weixin.qq.com/s/d9QCoBP6kV9VSWvVldVVwA
参考https://blog.csdn.net/raul575_li/article/details/80801312
具体实现代码:
此处代码是按照设计图为宽度360dp,高度667dp进行处理的,如果设计图给出的dp不同,要以实际dp为准。
packagecom.screen.density.utils;
importandroid.app.Activity;
importandroid.app.Application;
importandroid.content.ComponentCallbacks;
importandroid.content.res.Configuration;
importandroid.support.annotation.NonNull;
importandroid.support.annotation.Nullable;
importandroid.util.DisplayMetrics;
/**
* 通过修改系统参数来适配android设备
* https://www.jianshu.com/p/4254ea9d1b27
*
* Created by Raul_lsj on 2018/6/6.
*/
publicclassDensity{
privatestaticfloatappDensity;
privatestaticfloatappScaledDensity;
privatestaticDisplayMetricsappDisplayMetrics;
publicstaticvoidsetDensity(@NonNullApplicationapplication) {
//获取application的DisplayMetrics
appDisplayMetrics=application.getResources().getDisplayMetrics();
if(appDensity==0) {
//初始化的时候赋值
appDensity=appDisplayMetrics.density;
appScaledDensity=appDisplayMetrics.scaledDensity;
//添加字体变化的监听
application.registerComponentCallbacks(newComponentCallbacks() {
@Override
publicvoidonConfigurationChanged(ConfigurationnewConfig) {
//字体改变后,将appScaledDensity重新赋值
if(newConfig!=null&&newConfig.fontScale>0) {
appScaledDensity=application.getResources().getDisplayMetrics().scaledDensity;
}
}
@Override
publicvoidonLowMemory() {
}
});
}
}
//此方法在BaseActivity中做初始化(如果不封装BaseActivity的话,直接用下面那个方法就好)
publicstaticvoidsetDefault(Activityactivity) {
setAppOrientation(activity,AppUtils.WIDTH);
}
//此方法用于在某一个Activity里面更改适配的方向
publicstaticvoidsetOrientation(Activityactivity,Stringorientation) {
setAppOrientation(activity, orientation);
}
/**
* targetDensity
* targetScaledDensity
* targetDensityDpi
* 这三个参数是统一修改过后的值
*
* orientation:方向值,传入width或height
*/
privatestaticvoidsetAppOrientation(@NullableActivityactivity,Stringorientation) {
floattargetDensity;
//获取状态栏高度
intbarHeight=AppUtils.getStatusBarHeight(activity);
if(orientation.equals("height")) {
targetDensity=(appDisplayMetrics.heightPixels-barHeight)/667f;
}else{
targetDensity=appDisplayMetrics.widthPixels/360f;
}
floattargetScaledDensity=targetDensity*(appScaledDensity/appDensity);
inttargetDensityDpi=(int) (160*targetDensity);
/**
*
* 最后在这里将修改过后的值赋给系统参数
*
* 只修改Activity的density值
*/
DisplayMetricsactivityDisplayMetrics=activity.getResources().getDisplayMetrics();
activityDisplayMetrics.density=targetDensity;
activityDisplayMetrics.scaledDensity=targetScaledDensity;
activityDisplayMetrics.densityDpi=targetDensityDpi;
}
}