cool hit counter It's time to upgrade the way you adapt your screen, Sooo!_Intefrankly

It's time to upgrade the way you adapt your screen, Sooo!

Original article address:


this onemonth (located) at Android In technical circles Screen adaptation this one The word exposure is pretty high of, because of What do you mean?? reason because of this one One after another in the month, several bigwigs have released Screen adaptation (statistics) correlation of essay, Announced their endorsement of Screen adaptation options

upper last week Blankj Teacher posts a strong endorsement of Today's headlines Screen adaptation options of essay , proposed a number of optimization solutions, and open source the relevant source code

last week Latin America The teacher is in Hungarian God posted an article on his public website detailing several mainstream screen adaptation schemes on the market and posted his smallestWidth qualifier adaptation scheme harmony Related source code ( It was actually released a long time ago), essay write of good, We suggest you check it out.

In fact, we are most concerned about is not how many kinds of screen adaptation program on the market, but their own project should choose which screen adaptation scheme, you can see that the two teachers finally choose the screen adaptation scheme is different

I'm going to break it down below, I do because of One just touched these two Screen adaptation options of lit. people eating melon balls, How did I come to verify that both Screen adaptation Feasibility of the programme, and how to base them on of excellent drawback to choose the one that best suits your project of Screen adaptation options

This is what I recommend to everyone of Screen adaptation framework, I was going to put it last. because of welfare of, I'm afraid people won't see it., So just put the link here, In advance to everyone

Github : Your Star is what keeps me going ✊

A Brief Introduction to Adaptation Solutions

(located) at Latin America teachers of essay in which two of the more classic of Screen adaptation options, (located) at I'm very impressed., I think most of the brothers have used it, (located) at me of In a development career also For a long time there was (located) at Use both of these Screen adaptation options

The first one is width and height qualifier adaptation, what is width and height qualifier adaptation?

├── src/main
│   ├── res
│   ├── ├──values
│   ├── ├──values-800x480
│   ├── ├──values-860x540
│   ├── ├──values-1024x600
│   ├── ├──values-1024x768
│   ├── ├──...
│   ├── ├──values-2560x1440

It's this kind, generating resource files with different resolutions under the resource file, and then referencing the corresponding ones in the layout file dimens I'm sure it still rings a bell.

The second one is Hungarian God of AndroidAutoLayout

Both of these options have been phased out of history, and I'm sure we all know why, so if you don't, we suggest looking at Latin America I'm not going to elaborate on these two options in the article, so I'm going to focus on the two most mainstream screen adaptation options now, the Today's Headlines adaptation option and the article

I suggest that you are not clear about these two options first look at these two articles, only clear what I am talking about, after I want to explain their principles, as well as to verify whether these two options really work, and finally for their in-depth comparison, for some of their shortcomings to give the corresponding solutions, absolutely dry goods

today's headlines Screen adaptation options


I've been told above that those who don't know about these two options should first read the two articles above, so I'm going to assume here that you've already read the articles above or have known about these two options before, so I won't elaborate on them in this article DPIDensity As well as some of the more basic points, the article above has covered them well enough

today's headlines Screen adaptation options of core principle (located) at in, Calculated from the following formula density

Current equipment Total screen width( unit because of pixels)/ Total width of the design plan( unit because of dp) = density

density It means 1 dp How many pixels of the current device

Why is it important to work out density, these harmony Screen adaptation What does it matter??

public static float applyDimension(int unit, float value,
                                       DisplayMetrics metrics)
        switch (unit) {
        case COMPLEX_UNIT_PX:
            return value;
        case COMPLEX_UNIT_DIP:
            return value * metrics.density;
        case COMPLEX_UNIT_SP:
            return value * metrics.scaledDensity;
        case COMPLEX_UNIT_PT:
            return value * metrics.xdpi * (1.0f/72);
        case COMPLEX_UNIT_IN:
            return value * metrics.xdpi;
        case COMPLEX_UNIT_MM:
            return value * metrics.xdpi * (1.0f/25.4f);
        return 0;

As we all know, whatever units you fill in the layout file will end up being converted to px , the system is converting the units you fill in anywhere in the project by the method above to px of

So we commonly use the px forward (mail) dp formula dp = px / density , which is based on the method above.density plays a crucial step in the arithmetic of the formula

To read the following, you also have to understand that the way today's headers are adapted, the default item in today's headers adaptation scheme can only be adapted with one of height or width as the base, and why it's not like AndroidAutoLayout The same, with height as height and width as width, while adapting

This leads to a present (located) at trickier of issues, Most of the commercially available of Android installations of The screen aspect ratio is not even consistent, especially now (located) at Lots of full screens of come out This. The problem is more serious, Different manufacturers launch of full-screen phone of The screen aspect ratio may not even be consistent

At this point we only take the height or width of which of a composition because of Benchmarking for adaptation, It'll work. of Avoid layout (located) at Inconsistent aspect ratio of Distortion on screen of issues

Once I understand this, I'll come back to densitydensity (located) at It is fixed on each device of,DPI / 160 = density The total px width / density of the screen is the total dp width of the screen

  • Device 1, with a screen width of 1080px480DPI Total screen dp Width. 1080 / (480 / 160) = 360dp
  • installations 2, screen Width. 1440560DPI Total screen dp Width. 1440 / (560 / 160) = 411dp

You can see the total number of screens dp widths (located) at different of The device is subject to change of But... we (located) at Fill in the layout of dp happen to But it's fixed. of

What will this lead to? Suppose we have a layout with a View of Width. 100dp In device 1, the View of the entire screen width 27.8% (100 / 360 = 0.278)

however (located) at installations 2 should View The width of the screen would only take up 24.3% (100 / 411 = 0.243 ), you can see this View The higher the pixels on the screen, thedp happen to Although it hasn't changed. But... With the screen of The actual percentage has instead occurred in a larger of variations, So the naked eye of View Results, It's gonna get smaller and smaller., This has led to the traditional of fill in dp of Screen adaptation The way in which this has been done has produced greater of inaccuracies

At this point we want to adapt perfectly, then we have to make sure that this View The same ratio to the screen on any resolution

What do we do at this point? Change each View of dp happen to? unrealistic, (located) at Dynamically calculated by code on each device View of dp happen to, Too much work.

If each View of dp happen to It's fixed. of, Then we just have to make sure that each device of screen total dp A constant width will ensure that each View The ratio to the screen remains the same across all resolutions, thus completing an equal scale adaptation, and this total screen dp The width, if it is still guaranteed to be the same as the width of the design, then we can fill in the layout directly according to the dimensions on the design dp happen to

The total px width / density of the screen is the total dp width of the screen

In this formula we want to ensure that screen of total dp widths harmony Total width of the design plan Consistent, and constant across all resolutions of the screen, what do we need to do? Total px width of the screen Each device is inconsistent This. happen to It's definitely going to change. of, That's when today's headline formula That's where it comes in handy.

Current equipment Total screen width( unit because of pixels)/ Total width of the design plan( unit because of dp) = density

This formula is a combination of the above formula of screen of total dp widths convert into Total width of the design plan The principles are the same, as long as density By calculating and making changes in real time based on different devices, you can ensure Total width of the design plan No change, and the adaptation is complete

Validation of programme feasibility

The above has been a very clear analysis of the principle, many articles just a stroke of this formula, the formula is very simple but we still want to know how this came about, so I will reverse the reasoning once, if still can not read, then I can only say that I tried my best, the principle is finished, then we come back to the scene to verify whether the program is feasible?

Assuming that the total width of the design plan is 375 dp , a View The dimensions on this design are 50dp * 50dp This. View of the width of the entire design plan 13.3% (50 / 375 = 0.133), Then let's verify it. (located) at Using Today's Headlines Screen adaptation options of circumstances This. View Does the ratio to screen width remain the same as in the design drawing on devices with different resolutions

Validation equipment 1

screen total Width. 1080 px , based on today's headline's formula to find density1080 / 375 = 2.88 (density)

this one 50dp * 50dp of View The system ends up converting both the height and width to px50dp * 2.88 = 144 px ( According to the formula dp * density = px)

144 / 1080 = 0.133View Actual width vs. Total screen width and the proportion of View The proportions in the design drawings are consistent (50 / 375 = 0.133 ), so the equal scaling is done

Total for certain equipment Width. 1080 px But... DPI Might it be different and will it have an impact on today's headline adaptation scheme? Actually, there's no basis for this scenario at all DPI work out density It is. Depending on your own formula work out of density So this has no impact on the headline scenario today

The above can only be determined for all screens with a total width of 1080 px devices, so let's try other resolutions

Validation equipment 2

screen total Width. 1440 px , based on today's headline's formula to find density1440 / 375 = 3.84 (density)

this one 50dp * 50dp of View The system ends up converting both the height and width to px50dp * 3.84 = 192 px ( According to the formula dp * density = px)

192 / 1440 = 0.133View Actual width vs. Total screen width and the proportion of View The proportions in the design drawings are consistent (50 / 375 = 0.133 ), so it also completes the equal scaling

Two different resolution devices have completed the equal scaling, proving that today's headline screen adaptation solution is effective on different resolution devices, if you still have doubts, you can try other resolution devices, in fact, in the end the resulting ratio will not have any deviation, are 0.133


  1. Very low cost of use, Very simple to operate, After using the program (located) at The page layout does not require additional of code harmony operations, This point can be finished abusing other Screen adaptation options
  2. The intrusiveness is very low, the solution is completely decoupled from the project, it doesn't rely on even one line of code from the solution when laying out the project, and the use of Android formal API , which means that when you encounter a problem that can't be solved and want to switch to another screen adaptation, you basically don't need to change the previous code, the whole switching process is done almost instantaneously, it's a lot less trouble, a lot of time is saved, and the cost of trial and error is close to 0
  3. Adapts controls from three-party libraries and system controls (not only Activity harmony FragmentDialogToast etc. all system controls can be adapted), as the modified density is global throughout the project, so with a single change, all parts of the project will benefit
  4. There will be no loss of performance


Nothing else is obvious at the moment of drawback, known (science) of drawback There is a, That's the third one. advantages, It is both this one options of advantages The same goes for drawback But... Just this one. drawback also Very deadly. of

Only one modification is required density, Project in of All places will be automatically adapted This. Seems to free up your hands, Reduces a lot of operations But... It actually reflects a drawback, That's a one-size-fits-all approach. of Adapting the entire project, But the range of adaptation is uncontrollable of

Isn't that nice?? That would have been nice. of But... apply to this one It's not a good idea., reason because of I'm up there of principle It is also analyzed This. The scheme relies on the design size But... Project in of System controls、 A tripartite library control、 such as non-our project design of control, they of The design size does not harmony Our project itself of The design size is the same

The problem arises when this adaptation scheme forces all controls to be adapted using our project's own layout dimensions, regardless of type. The problem becomes more serious when the size of a system control or a three-way library control is very different from the size of our project's own design

A chestnut.

Assuming a three-way library of View , which the authors designed as 100dp * 100dp, plan of utmost Width. 1000dp This. View The scale in the design drawing is 100 / 1000 = 0.1 It means this. View of widths (located) at The design takes up the entire width of 10% , if we want to complete the equal scale adaptation, then this three-way library View The ratio to the total width of the screen, on all devices, must be maintained at 10%

At this point on a project using the Today's Headers screen adaptation scheme, the maximum width of the design image set if 1000dp And this three-way library. View The project can be perfectly adapted to the project itself, but when the maximum width of our project's own design drawing is not 1000dp It is. 500dp When.100 / 500 = 0.2 and, as you can see, the scale has changed considerably from 10% rise because of 20% Apparently, this three-way library View Higher than the author of prospect, It's bigger than before.

This is a very serious problem caused by the inconsistent size of the two designs, and the bigger the difference in size between the two designs, the more different the adaptation will be


Option 1

Resize the design, reason because of Tripartite libraries may be remotely dependent of, Unable to modify the source code, And it won't be possible to adapt a three-way library to our project of Design size, So it's up to us to make changes ourselves, To adapt to the tripartite library of Design size, We will project ourselves of Design size modifications because of this one A tripartite library of Design size, you can complete the project itself harmony A tripartite library of Fit

At this point the project's layout dimensions are modified, so the dp values in the project layout file should also be scaled up or down according to the modified layout dimensions, keeping them at the same scale as in the previous layout

But it is not worthwhile to modify the dimensions of the entire project's design drawings to adapt a three-party library, so this solution supports the use of Activity for the unit to modify the dimensions of the design drawings, equivalent to each Activity All can customize the design drawing size, as some Activity The tripartite library is not used View , there would be no need for custom sizes, so each Activity have control of speech, these also The most flexible of

But there's a problem when a Activity Uses multiple tripartite libraries with different design drawing sizes View The same problem will occur with the above, which can only be barely mitigated by changing the design to a size that is more compromised with several three-way libraries

Option 2

The second option is the simplest of, also press Activity for the unit, cancel the current Activity to an alternative adaptation scheme

The problem in use

some essay in which today's headlines are mentioned Screen adaptation The scheme can fill in the dimensions of the design drawing as a px the width and height of the unit so that we can fill in the design directly in the layout file px happen to, Omitting the need to include px convert to dp of time (most companies' design drawings are only labeled px happen to), And it still fits perfectly.

But I suggest you never do that., Or honest of in order to dp Fill in for the unit dp happen to, because of What's that??

Fill in directly px Although the layout is cool at first, the hole is already buried and will make you feel good later, what are the holes?

the first hole

This will undoubtedly make the project strongly coupled this one options, When you encounter can not solve of The question wants to be switched because of other Screen adaptation options of time,layout The file used to be filled in px The values will all be used as dp

Like you of The design is practical Width. 1080px , you don't convert to 360dp (1080 / 3 = 360) Instead, it will be straightforward to 1080px As the dimensions of the design drawings for this scheme, then you are in layout The document is also filled in with all the design drawings marked on the px happen to But... The unit is dp

One (located) at On the design 300px * 300px of View You can go straight in layout Fill in the file because of 300dp and since this scheme can be dynamically changed density The reason can still do the same proportion adaptation, very cool!

But you mustn't forget that this way you are strongly coupled to this scheme, because when you don't use this schemedensity It's immutable!

A chestnut.

When using this scheme, the screen width is 1080px on the device, fill in the design drawing width directly as 1080 , according to today's headline formula

Current equipment Total screen width / Total width of the design plan = density

At this point it is drawn density for 1 (1080 / 1080 = 1 ), so you're in layout The file you fill in 300dp At last forward (mail) change because of px also 300px (300dp * 1 = 300px According to the formula dp * density = px)

(located) at this one options of Perfect with the help of, harmony The design is identical to the finished adaptation

But when you don't use this option, thedensity The conversion formula becomes the official DPI / 160 = density, (located) at this one screen Width. 1080px480dpi on the equipment of thedensity It is fixed at 3 (480 / 160 = 3)

This is the time to come back to your previous work on layout Document completed in dp , converted to px because of 900 px (300dp * 3 = 900px According to the formula dp * density = px)

Originally on the design drawings for 300px of View This time, however, it reached a staggering 900px , 3 times the difference, congratulations, you've been strongly coupled to this scenario, you either all layout Change the files all over again or continue with the program

Second pit

Second pit Actually, just now. (located) at said above of Today's Headlines Adaptation Solution of drawback, The problem becomes more serious when the size of a system control or a three-way library control is very different from the size of our project's own design

If you fill in the form directly with px This is the size of the design, which, needless to think, must be different from the size of all the three-party libraries and system controls, and the difference is very large, at least two or three times larger, when you pop a Toast You can clearly see that it's much smaller than before, and you can say it's a world of difference, using other three-way libraries View, also the same as of, It's going to be much smaller

Because of you px Fill in the dimensions of the design plan for the unit, but people use the dp Can the gap be small? If you're honest and use dp Even if the dimensions of the three-party library are not the same as your project's own design, the difference is not large, to a certain extent, basically do not need to adjust, can be negligible, and many three-party library design dimensions are actually the same as those few popular sizes, and most likely the same as your project's own design dimensions


I can see what I'm saying of Very detailed, Can be said to be more official than today's headlines as well as any blog post of It's all clear, from principle to the excellent drawback And then again solution Readily available, reason because of Space is limited, If I still want to put smallestWidth Qualifier adaptation scheme write of So detailed, That's an estimate of this one essay It's got to be ten thousand words

So I've grouped this screen adaptation article into a series of three, the first of which goes into detail today's headlines Screen adaptation options The second article goes into detail smallestWidth constraint adaptation scheme The third post details an in-depth comparison of the two options and how to choose between them, and posts my findings based on today's headlines Screen adaptation options optimize of Screen adaptation framework AndroidAutoSize

today's headlines Screen adaptation options The official published core source code is less than 30 lines, but my source code for this framework has 1500 The above line, while retaining the original features added a lot of functions and features, the functions have increased a lot, but the use has become easier


As long as this step fills in the height and width of the design to dp As a result, you do nothing and the framework begins to fit

You can see in advance how I encapsulate harmony optimize of, Behind me. of Part III essay will give this one framework of principle analyse, Stay tuned

Hello My name is Jessyan, if you like my articles, you can follow me on the following platforms

My blog will soon move and sync to the Tencent Cloud+ community and invite you to join it: -- The end

1、New DeepMind results uninterpretable neurons are no less useful than interpretable ones
2、Invincible bull cheat software download invincible bull cheat download cheat auxiliary universal version
3、Weibo Data Center 2017 China ECommerce Industry Research Report
4、ol4vs database microsoft app is released
5、SEO optimization a few aspects of website code optimization you often dont pay attention to

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送