Juejin. Im/Post /684490…

Here’s how to upgrade your screen adaptation this year! Welcome to repost and share:

  • It’s time to upgrade your screen adaptation. (I) – Toutiao adaptation scheme
  • It’s time to upgrade your screen adaptation. (2) -smallestWidth qualifier adaptation solution
  • Toutiao screen adaptation ultimate version officially released!
  • Why is the design of AndroidAutoLayout wrong?

Join technical exchange QQ group 455850365

preface

In the previous two articles, I introduced the principle of toutiao adaptation scheme and SmallestWidth qualifier adaptation scheme in detail, verified their feasibility, and summarized their advantages and disadvantages. It can be said that these two schemes are both excellent and mainstream Android screen adaptation scheme at present. And they all already have a certain user base

But for some just contact with the two schemes of friends, must be more or less still don’t know how to choose the two scheme, although I in the previous article gives their respective advantages and disadvantages, but did not use a unified standard for more detailed comparison, so also can’t do more image is the embodiment of their advantages and disadvantages, So I’m going to compare them using the same standard, and see how they compare

Scheme comparison

I always firmly believe in the two scheme, and not as a single standard can judge who must be better than good, because they all have their own advantages and disadvantages, are not perfect, from the more objective point of view, they can’t be the best that anyone, only can made clear their respective advantages and disadvantages, know what is in the advantages and disadvantages of them I can accept, What can I not accept, and can I compromise some of the advantages to choose the best screen fit for my project

It doesn’t make any sense to simply argue about who is the best Android screen adaptation solution. Everyone has different needs, different perspectives and different criteria. What you can accept may not be acceptable to him, but what you find unacceptable to him may be acceptable to him. It’s so hard to make a point that everyone can accept! Therefore, I just list their comparison items and results here, and try to be objective as much as possible. Please decide the final selection result by yourself. If there are any missing comparison items, please add them!

Compare the project Comparison Object A Comparing the results Comparison object B
Adaptation effect (the higher the better) Toutiao adaptation scheme material SW qualifier adaptation scheme (there will be some error on uncovered models)
Stability (the higher the better) Toutiao adaptation scheme < SW qualifier adaptation solution
Flexibility (the higher the better) Toutiao adaptation scheme > SW qualifier adaptation solution
Scalability (the higher the better) Toutiao adaptation scheme > SW qualifier adaptation solution
Invasive (the lower the better) Toutiao adaptation scheme < SW qualifier adaptation solution
Use cost (the lower the better) Toutiao adaptation scheme < SW qualifier adaptation solution
Maintenance costs (the lower the better) Toutiao adaptation scheme < SW qualifier adaptation solution
Performance loss The toutiao adaptation has no performance loss = There is no performance cost to the SW qualifier adaptation scheme
Side effects Toutiao adaptation will affect some three – party library and system controls material The SW qualifier adaptation scheme affects the size of the App

It can be seen that the SmallestWidth qualifier adaptation scheme and Toutiao adaptation scheme have the same effect. In the previous article, I also calculated their accuracy by formula. SmallestWidth qualifier adaptation scheme can also be adapted when running on uncovered models. However, there will be a certain error, so the adaptation accuracy of Toutiao adaptation scheme is indeed slightly higher than the SmallestWidth qualifier adaptation scheme, but as long as the SmallestWidth qualifier adaptation scheme reasonable allocation of resource files, the adaptation effect gap should not be large

SmallestWidth qualifier adaptation program is the main stability, in the process of operation will rarely appear security risks, the adaptation range is controllable, will not produce other unknown effects, and The toutiao adaptation program is mainly to reduce the development cost, improve the development efficiency, more flexible use, but also to meet more expansion needs, In a simple word, the two brothers, one for stability, one for fast, well, I will introduce so much, choose yourself!

AndroidAutoSize

origin

Now I will start to introduce my screen adaptation framework optimized according to the screen adaptation scheme of jinri toutiao, AndroidAutoSize, you must not think that I launched the screen adaptation framework of AndroidAutoSize is optimized according to the screen adaptation scheme of jinri toutiao, I personally support the view that Jinri Toutiao’s screen adaptation scheme is the best Android screen adaptation scheme. It is indeed excellent, but it also has a lot of disadvantages. My most true opinion has been expressed above, as to why I want to package a screen adaptation framework based on Jinri Toutiao’s screen adaptation scheme. For the following reasons:

  • SmallestWidth qualifier adaptation there are several excellent open source solutions that can meet all of our daily development needs

  • The official technical team of Toutiao only released the articles and core code of the toutiao screen adaptation solution, but did not create a public repository on Github. A new solution must have a process of growth and iteration, during which a public community is required to gather all users. Can let all use the solution users in the above communication, we summarize together, fill the pit together, so as to make the solution more mature and stable, this is the power of open source

  • The core code released by the official technical team of Toutiao can not meet all my needs, and other open source projects and solutions based on the screen adaptation solution of Toutiao can not meet all my needs, but I have a better implementation idea

  • MVPArms needs a screen adaptation framework that works well and has a low switching maintenance cost to help users quickly replace AndroidAutoLayout with a low cost and effort

I suggest that you can actually experience the Toutiao screen adaptation scheme and the SmallestWidth qualifier adaptation scheme to feel their similarities and differences. My suggestion is that you can first use the Toutiao screen adaptation scheme in your project to feel its use and adaptation effect. Today’s header screen adaptation is very low intrusive, if you encounter any problems that can not be solved in the process of use, you can immediately switch to other screen adaptation, in the process of switching does not cost much work, trial and error cost is very low

If you use the SmallestWidth qualifier in your project and you run into problems, you may need to switch to another Layout. Each Layout file contains a large number of References to Dimens. Think about how much work it would take to change, and this is the most deadly problem caused by being too invasive

If you want to experience toutiao screen adaptation, don’t miss AndroidAutoSize! Just one step to access the item, here is the address of AndroidAutoSize:

Github: Your Star is what keeps me going ✊

Relationship with toutiao screen adaptation scheme

AndroidAutoSize and jinri tiao screen adaptation solution, equivalent to the relationship between the car and the engine, jinri tiao screen adaptation solution official code, only to achieve the relevant logic to modify the system density, which does play the most critical role in the screen adaptation, but it is far from enough

In order for the user to be able to use the solution more foolishness, and to be able to cope with all the complex requirements in daily development, the framework also needs to consider the usability and rationality of the API, the extensibility and flexibility of the framework, the comprehensiveness of the functionality, and the legibility of comments and documentation

So I brought my these standards on the Internet to search for a long time, found that there is no an open source framework or solution can meet all my standards, most of them are still stays in the headlines today will screen adaptation scheme Encapsulated into a utility class to introduce phase of the project, so on the expansion of the function limit, and the use of the user experience is not good, What I wanted to do was a comprehensive product-level screen adaptation framework, which was still far from my original idea, so I had to do it myself and implement all my ideas, which resulted in AndroidAutoSize

After writing the AndroidAutoSize framework, because of the toutiao screen adaptation scheme has a more in-depth understanding, so I wrote SAO years your screen adaptation mode should be upgraded! (I) – Toutiao adaptation scheme to help you understand the screen adaptation scheme of Toutiao more clearly

Relationship with AndroidAutoLayout

AndroidAutoSize is very similar to Hongshen’s AndroidAutoLayout in name, and is also very similar in the way of filling in the design size, plus the screen adaptation series articles I wrote were also published on hongshen’s official account, So a lot of people think that AndroidAutoSize is an upgrade to AndroidAutoLayout, which I can’t laugh or cry 😂, so I’m just going to say, hi, my name is JessYan, AndroidAutoSize is an upgrade to AndroidAutoLayout, but I wrote it, so keep an eye on it

AndroidAutoSize and AndroidAutoLayout have very different principles. For example, AndroidAutoLayout only uses px as the layout unit, whereas AndroidAutoSize does the opposite. In the layout, all units dp, SP, PT, IN, mm are supported except px, but this means that AndroidAutoSize and AndroidAutoLayout can coexist without affecting each other. So old projects using AndroidAutoLayout can also safely introduce AndroidAutoSize, slowly complete the screen adaptation frame switch

The name Of the framework is AndroidAutoSize, firstly, to pay tribute to the contribution AndroidAutoLayout has made to Android screen adaptation, and secondly, to be an influential framework in Android screen adaptation

structure

I had already said a lot on open source framework and solution, just put today’s big screen adaptation scheme Simple packaging into a utility class then project are introduced, then a lot of people would have said Today’s headline screen adaptation scheme The official full are less than 30 lines of code, you don’t keep it encapsulated into a utility class, the encapsulated into? How do you encapsulate it? Here’s a look at the overall structure of AndroidAutoSize

├ ─ ─ external │ ├ ─ ─ ExternalAdaptInfo. Java │ ├ ─ ─ ExternalAdaptManager. Java │ ─ ─ internal │ ├ ─ ─ CancelAdapt. Java │ ├ ─ ─ Java │ ├─ Unit │ ├─ Bass exercises. Java │ ├─ bass Exercises. Java │ ├─ bass Exercises LogUtils. Java │ ├ ─ ─ Preconditions. Java │ ├ ─ ─ ScreenUtils. Java ├ ─ ─ ActivityLifecycleCallbacksImpl. Java ├ ─ ─ AutoAdaptStrategy. Java ├ ─ ─ AutoSize. Java ├ ─ ─ AutoSizeConfig. Java ├ ─ ─ DefaultAutoAdaptStrategy. Java ├ ─ ─ DisplayMetricsInfo. Java ├ ─ ─ FragmentLifecycleCallbacksImpl. Java ├ ─ ─ InitProvider. JavaCopy the code

AndroidAutoSize has developed into a comprehensive screen adaptation framework with 18 class files and thousands of lines of code through continuous optimization and expansion according to the official 30 lines of code of The screen adaptation scheme of Today’s Headlines. In the process of iteration, many functions have been improved and optimized. Compared to the original code published by toutiao screen adaptation scheme, AndroidAutoSize is more stable, more easy to use and more powerful, welcome to read the source code, very detailed comments oh!

Function is introduced

AndroidAutoSize is very simple to use, you only need to fill in the design size this step to access the project, but it should be noted that AndroidAutoSize has two types of layout units to choose from, one is the main unit (DP, SP), one is the secondary unit (PT, in, mm), Both units are oriented to different application scenarios and have their own advantages and disadvantages

  • The main unit: Use DP, SP for the unit layout, the least invasive, will affect the layout effect of other third-party library pages, third-party library controls and system controls, but AndroidAutoSize also through this feature, ExternalAdaptManager is used to implement the function of adapting third-party libraries without modifying the source code of third-party libraries

  • Deputy units: The use of PT, IN, MM for the unit layout, invasive, high support for the old project is good, will not affect the layout effect of the other three party library page, three party library control and system control, can be completely shielding the density caused by all the unknown and known problems, However, AndroidAutoSize will not be able to adapt to the three-party libraries

You can choose one of the main units and the secondary units as the layout unit according to your application scenario. It is suggested that people who want to introduce old projects and pay attention to stability should use the secondary unit. People who just want to try this framework and may switch to other screen adaptation schemes should use the main unit at any time

In fact, AndroidAutoSize supports both primary and secondary units, but the purpose of AndroidAutoSize is to allow users to switch between primary and secondary units. Because the workload of changing units may be very huge, it can not be completed immediately, but the leader requires that the unit should be packaged and put online immediately. At this time, it can play a good transition role

The main unit

The main unit Demo is in Demo

The basic use

When you introduce AndroidAutoSize into your project, just fill in the design size in your app’s AndroidManifest.xml and without much configuration (if you don’t have any other customization requirements), AndroidAutoSize will run automatically, as shown below 👇

<manifest>
    <application>            
        <meta-data
            android:name="design_width_in_dp"
            android:value="360"/>
        <meta-data
            android:name="design_height_in_dp"
            android:value="640"/>           
     </application>           
</manifest>
Copy the code

Design_width_in_dp and design_height_in_dp must be in units of DP when using the main unit. If the designer gives you a drawing with only px dimensions (there are a lot of UI tools that can automatically label dp dimensions), Please use the formula DP = px/(DPI / 160) to convert the px size to the DP size. If you don’t know what DPI is? Then please take the DPI of your test machine as the standard. If you don’t know how to get the DPI of the equipment? If you can’t find the device’s DPI, just divide the px size by 3 or 2

If you just want to use the basic features of AndroidAutoSize, the use of AndroidAutoSize ends here. This step will help you access AndroidAutoSize in the simplest way, but as a comprehensive screen adaptation framework, On the basis of the guarantee function of simplicity at the same time, also must ensure that the complex requirements can be resolved within the framework, so as to achieve a small loop, so the following content is full of predecessors on pit stepping out some necessary function, if you don’t have this requirement, or trouble, can skip, on-demand view or cooperate to read the following Suggestions and Demo, The effect is much better

Matters needing attention

  • In androidManifest.xml, each control’s size needs to be converted to a dp size in the same way that you convert the px size of the design drawing to the DP size. Never fill in the dp dimensions in androidManifest.xml and then continue to fill in the px dimensions in the layout

  • Design_width_in_dp and design_height_in_dp both need to be filled in, but AndroidAutoSize only uses width and height as a reference. AutoSizeConfig#setBaseOnWidth(Boolean) this means that only one of the layouts will be the same height and width as the design, while the other will be different. Why not, like AndroidAutoLayout, have both the height and width perfectly proportioned to the design? This is also very simple, you can’t ensure that all equipment is the ratio of height to width is and you design the height to width ratio on the consistent, especially under the condition of full screen now fully launched, if don’t do that here, when your program is running with the design height to width ratio of equipment, layout can appear serious deformation, the risk is very big, please Here,

How is auto-running done?

A lot of people wonder why users just fill in the meta-data tag in androidManifest.xml and do nothing else, and AndroidAutoSize runs automatically. And automatically parse the design drawing size filled in androidManifest.xml when the App is started, many people here can’t believe that I really only need to fill in the design drawing size frame can run normally? What kind of dirty technology was used?

There’s no dark technology involved, but it’s pretty simple. You just declare a ContentProvider, launch the framework in its onCreate method, and when your App starts, The system will automatically instantiate your declared ContentProvider in the main process of your App and call its onCreate method. This will be executed before Application#onCreate. You can do some initialization.

The important thing to note here is that if your project has multiple processes, the system will only instantiate one of your declared ContentProviders in the main process. It will not instantiate the ContentProvider in any non-main process. If the ContentProvider is not instantiated in the current process, The ContentProvider#onCreate will not be called and your initialization code will not be executed in the current process. In this case, the ContentProvider#query will be called in the Application#onCreate. The ContentProvider is instantiated in the current process (only one instance is guaranteed in each process), so if you need to do screen adaptation across multiple processes, You need to call the AutoSize#initCompatMultiProcess method in Application#onCreate

Use the advanced

AndroidAutoSize doesn’t require much configuration, just fill in the design size in androidManifest.xml, but AndroidAutoSize has a lot of options for you to configure. Do your best to meet all your extension needs in your daily development

All of the global configuration options are covered in the Demo, and each API is also commented in detail, so I won’t go into much detail here

Custom Activity

The design size filled in in androidManifest.xml is the global design size for the entire project, but if for some reason the designer makes a separate drawing for some Activity page, What should I do if the design size of this page is different from the size filled in in androidManifest.xml? The first method of CustomAdapt is to change the size of the current page’s design. The second method is to switch the adaptation criteria for the current page, as explained in the comments below

public class CustomAdaptActivity extends AppCompatActivity implements CustomAdapt {

	 /** whether to use the same ratio of width (in order to ensure proper adaptation on screens with different aspect ratios, you must use either the width or the height as the reference) **@return {@codeTrue} To fit by width, {@codeFalse} to fit by height */
    @Override
    public boolean isBaseOnWidth(a) {
        return false;
    }

	 * <p> * Return the size of the design on the design drawing, in units of dp * {@link#getSizeInDp} must be matched with {@link#isBaseOnWidth()}@link# isBaseOnWidth ()} returns {@code true}, {@link#getSizeInDp} should return the total width of the design drawing@link# isBaseOnWidth ()} returns {@code false}, {@link#getSizeInDp} should return the total height of the drawing * if you do not need to customize the design size on the drawing and want to continue using the design size filled in in the AndroidManifest, {@link#getSizeInDp} returns {@code 0}
     *
     * @returnThe design size on the design drawing, in unit dp */
    @Override
    public float getSizeInDp(a) {
        return 667; }}Copy the code

If an Activity wants to give up adaptation, simply make the Activity implement the CancelAdapt interface. For example, changing the density affects the layout of some Activity pages in an old project. You can then have the Activity implement the CancelAdapt interface

public class CancelAdaptActivity extends AppCompatActivity implements CancelAdapt {}Copy the code

Custom fragments

Fragments can be customized in the same way as activities, except that support for fragments must be enabled during App initialization

AutoSizeConfig.getInstance().setCustomFragment(true);
Copy the code

Implement CustomAdapt

public class CustomAdaptFragment extends Fragment implements CustomAdapt {

    @Override
    public boolean isBaseOnWidth(a) {
        return false;
    }

    @Override
    public float getSizeInDp(a) {
        return 667; }}Copy the code

Implement CancelAdapt

public class CancelAdaptFragment extends Fragment implements CancelAdapt {}Copy the code

Adaptation three-party library page

You can use ExternalAdaptManager to adapt all pages (activities, fragments) of the third-party library without modifying the source code of the third-party library.

Because AndroidAutoSize requires that pages that need to customize adaptation parameters or cancel adaptation must implement CustomAdapt and CancelAdapt, the problem is that the third-party libraries are remotely dependent, so we can’t modify the source code. How can we make the pages of the three-party library also implement custom adaptation parameters or unadaptation? Don’t worry, this needs AndroidAutoSize has also been considered for you, of course, will not let you download the three party library to the local and then change the source code!

  • Through ExternalAdaptManager# addExternalAdaptInfoOfActivity (Class, ExternalAdaptInfo) is an alternative to implementing CustomAdapt by adding the classes and custom adaptation parameters that need to be customized to the method, which is shown here with detailed comments

  • Instead of implementing CancelAdapt, add the canceladaptofactivity (Class) method to the ExternalAdaptManager#addCancelAdaptOfActivity(Class) method, which is shown here with detailed comments

Note that the ExternalAdaptManager method can add any class, but only supports activities and fragments, and the ExternalAdaptManager method supports chained calls, so that multiple pages can be added continuously

Of course, ExternalAdaptManager can be used not only for pages of third-party libraries, but also for activities and fragments in your own projects to customize adaptation parameters and cancel adaptation without implementing CustomAdapt or CancelAdapt

Deputy unit

The application scenarios of sub-units have been introduced before, so here is how to use the sub-units directly. Is the Demo of sub-units in demo-subunits

The basic use

First of all, just like the main unit, you need to fill in the design drawing size in the App’s AndroidManifest.xml, but different from the main unit, When using sub-units design_width_in_dp and design_height_in_dp do not need to be dp, you can directly fill in the dimensions of the design drawing px, and the size of each control in the layout file can also directly fill in the dimensions of the design drawing px. There is no need to convert PX to DP, which is one of the features of sub-units that can help you improve your development efficiency

<manifest>
    <application>            
        <meta-data
            android:name="design_width_in_dp"
            android:value="1080"/>
        <meta-data
            android:name="design_height_in_dp"
            android:value="1920"/>           
     </application>           
</manifest>
Copy the code

AndroidAutoSize provides three types of secondary units, pt, IN and MM, for users to choose, so to use secondary units, you also need to initialize the APP, Use the UnitsManager#setSupportSubunits(Subunits) method to select a subunit that you like. Then use this subunit in your layout file. The effect is the same for all three types of Subunits

Because the use of secondary units is in order to completely shield modified density caused by the three party library page, three party library control and system control layout effect, It is recommended to call UnitsManager#setSupportDP(false) and UnitsManager#setSupportSP(false) to disable AndroidAutoSize support for dp and sp. AndroidAutoSize why not use the sub-unit when the default to disable support for DP, SP? This is because allowing support for both primary and secondary units helps the user make a better transition between primary and secondary units, as mentioned earlier

The detailed use of UnitsManager is shown in demo-subunits, and the comments are very detailed

The customActivityFragment

The way to customize activities and fragments with minor units is the same as with primary units, so I won’t go into that here

Adaptation three-party library page

If your project is using secondary units and has disabled support for primary units (DP, SP), the ExternalAdaptManager will not work on the pages of the third-party libraries, only on the pages of your own project, unless the third-party libraries also use secondary units (PT, IN, mm) for layout

In fact, the reason why the deputy unit can completely shield modification of density caused by the three party library page, three party library control and system control layout effect, is because the three party library page, three party library control and system control basically use dp, SP layout, So as long as AndroidAutoSize turns off support for DP and SP, and instead uses a secondary unit for layout, you can completely shield the impact of changing density on the layout effect of third-party library pages, third-party library controls and system controls

However, this also means that the ExternalAdaptManager does not work on third-party library pages using secondary units

Live preview of layout

In many cases, the default preview device provided by Android Studio does not fully display our design drawings, so we need to create our own analog devices. Please see here for the method of creating analog devices of DP, PT, IN, and MM units

conclusion

AndroidAutoSize has been through 240+ commit, 60+ issues, and 6 versions, but it has been stabilized. The first official release of AndroidAutoSize was released last week, thanks to the thousands of users who have connected AndroidAutoSize to their projects. Thanks for their trust, the original purpose of AndroidAutoSize is to provide a gathering place for all users of Jinri Toutiao’s screen adaptation solution, so we will continue to collect and solve common problems of Jinri Toutiao’s screen adaptation solution. Let toutiao screen adaptation scheme become more mature and stable

This concludes the third article in this series, which heralds the end of the series, and suggests that, in combination with the first article, it’s time to upgrade your screen adaptation! (a) – Toutiao adaptation solution together, so that you can have a deeper understanding of the Toutiao screen adaptation solution, if you can read the whole series of articles, you will definitely have a rapid improvement in the field of Android screen adaptation knowledge!

When your project needs to switch to a certain framework, how will you look at, analyze, compare existing open source solutions, and have enough reasons to choose or optimize a solution that is most suitable for your project? Actually the whole series can be thought of as how to choose the same type I open source solution, the process of you later when you have the same choice can be reference to my way of thinking to deal with, of course, if the interviewer asked you screen adaptation of related questions, could you me how to choose, the process of analysis, compare the existing solution and the core knowledge points in the article to the interviewer, That’s a lot more valuable than if you just said that I use such and such open source library

The public,

Search and follow my public account JessYan to learn and make progress together. If there is any update of the framework, I will inform you in the public account as soon as possible


Here’s how to upgrade your screen adaptation this year! Welcome to repost and share:

  • It’s time to upgrade your screen adaptation. (I) – Toutiao adaptation scheme
  • It’s time to upgrade your screen adaptation. (2) -smallestWidth qualifier adaptation solution
  • Toutiao screen adaptation ultimate version officially released!
  • Why is the design of AndroidAutoLayout wrong?

Hello, my name is JessYan. If you like my articles, you can follow me on the following platforms

  • Personal homepage: Jessyan.me
  • Making: github.com/JessYanCodi…
  • The Denver nuggets: juejin. Im/user / 976022…
  • Jane: www.jianshu.com/u/1d0c0bc63…
  • Weibo: weibo.com/u/178626251…

— The end