android屏幕适配终极方案

2019-08-21  本文已影响0人  GoodWen

1,屏幕适配类


public class Density {

    private static final float WIDTH =320;//参考设备的宽,单位是dp

    private static float appDensity;//表示屏幕密度

    private static float appScaleDensity;//字体缩放比例,默认appDensity

    public static void setDensity(final Application application, Activity activity) {

         DisplayMetrics displayMetrics = application.getResources().getDisplayMetrics();

           if (appDensity ==0) {

            //初始化赋值操作

            appDensity = displayMetrics.density;

            appScaleDensity = displayMetrics.scaledDensity;

            //添加字体变化监听回调

            application.registerComponentCallbacks(new ComponentCallbacks() {

                 @Override

                 public void onConfigurationChanged(Configuration newConfig) {

                   //字体发生更改,重新对scaleDensity 进行赋值

                    if (newConfig !=null && newConfig.fontScale >0) {

                           appScaleDensity =application.getResources().getDisplayMetrics().scaledDensity;

                    }

                  }

                 @Override
                 public void onLowMemory() {

                 }
           });
        }

        //计算目标值 Density ScaleDensity DensityDpi

        float targetDencity = displayMetrics.widthPixels /WIDTH;//1080 / 360 = 3.0

        float targetScaleDensity = targetDencity * (appScaleDensity /appDensity);

        int targetDensityDpi = (int) (targetDencity *160);

        //替换activity的 Density ScaleDensity DensityDpi

        DisplayMetrics dm = activity.getResources().getDisplayMetrics();

        dm.density = targetDencity;

        dm.scaledDensity = targetScaleDensity;

        dm.densityDpi = targetDensityDpi;

    }

}

2,在Application中使用

public class Appextends Application {

    @Override

    public void onCreate() {

        super.onCreate();

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

           @Override

            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

              Density.setDensity(App.this, activity);

            }

           @Override

            public void onActivityStarted(Activity activity) {

            }

           @Override

            public void onActivityResumed(Activity activity) {

             }

           @Override

            public void onActivityPaused(Activity activity) {

             }

           @Override

            public void onActivityStopped(Activity activity) {

             }

           @Override

            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

             }

           @Override

            public void onActivityDestroyed(Activity activity) {

            }

            });

    }

}
上一篇下一篇

猜你喜欢

热点阅读