I recently researched the android screen adaptation scheme. In fact, there are many adaptations on the Internet, but I feel that the writing is very tall, but when I use it, the layout is disordered and cannot be adapted to various models.
Xiaosheng Bucai wrote a simple adaptation scheme. The dp in your layout still uses your dp, nothing needs to be changed, you only need a few lines of code to get it done
Of course, this adaptation cannot be a panacea for all mobile phones . After all, mobile phones on the market are a hodgepodge of hodgepodge. As a programmer, I express my heartache . Well, I will stop talking nonsense. I believe you have already searched a lot of nonsense articles. now ; ok I'll start my show, the crowd applaud
Let's take a look first
Density Resolution
ldpi 0.75 320*240
mdpi 1 480*320
hdpi 1.5 800*480
xhdpi 2.0 1280*720
xxhdpi 3.0 1080x1920
We are going to use this class
This is just the core code
activityLifecycleCallbacks = new Application.ActivityLifecycleCallbacks() { //This is to monitor all activities @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { density(activity, mWidth,mHeight); //We get the activity here } @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) { } };
private static void density(Context context, float width , float height){ Point point = new Point(); ((WindowManager)context.getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getSize(point); //Get the value of the screen context.getResources().getDisplayMetrics().density = point.x/width*2f; //context is the width of the screen where we get the context setting density value in the activity/the mainstream resolution we set by ourselves*2f (representing this mainstream The density value of the resolution is based on 720*1280) context.getResources().getDisplayMetrics().density = point.y/height*2f; }
public void start(){ resetDensity(mApplication, mWidth,mHeight); //The parameters inside are saved by the constructor of the class mApplication.registerActivityLifecycleCallbacks(activityLifecycleCallbacks); }