Android screen Adaptation Scheme

Source: Internet
Author: User
Tags benchmark

Reprint please indicate the source:
http://blog.csdn.net/lmj623565791/article/details/45460089;
This article is from: "Zhang Hongyang's Blog"

1. Overview

When you are developing Android, you will certainly feel that screen fitting is a particularly painful thing, the various screen sizes to match up the egg is extremely painful. If we change the angle we look at this problem, do not know whether you have learned the Web front-end development, or that everyone is not unfamiliar with the Web page, in fact, the problem of adaptation in the design of Web pages in theory also exists, why so to say? The resolution of the computer's monitor, including the resolution of the phone, I dare say that the type of resolution is far more than the resolution of the Android device, then there is a very strange phenomenon:

Why has the Web page designer never said that Nima is a hassle?

So, what is the reason, so that the design of the Web page in a variety of resolutions can still give users a high-quality experience? With this doubt, I asked the next daughter-in-law (front-end staff), daughter-in-law wide eyes asked me: What is the adaptation? FC, it seems that there is no such problem. Later I carefully asked, she told me, oh, this size ah, I am set to 20% ~ ~ traced, in fact, is a reason, the page provides a percentage calculation size.

Similarly, after you get the UI to the design diagram, is not complaining about you are the PX, I project with DP, what, and UI staff explained that the UI sister does not understand. Then this example can also solve the contradiction between Android engineer and UI sister ~ui give a fixed-size design draft, and then you write the layout of the time without thinking, no brain copy the above identified pixel value, you can achieve the perfect fit, ideal abundance not plump ~ ~.

However, the adaptation scheme given by Android for different screens is DP, so what is the difference between DP and percent?

2. DP vs percent
    • Dp

Let's first look at the definition of DP:

Density-independent Pixel (DP) independent pixel density. The standard is 160dip. That is, 1DP corresponds to 1 pixel, the calculation formula such as: PX = DP * (dpi/160), the larger the screen density, 1dp corresponding pixel points more.
In the formula above, there is a dpi,dpi dpi is dots per inch (the number of dots printed in inches), that is, when the device has a DPI of 160 1px=1dp;

Well, the above concepts do not remember the matter, just remember that a bit of DP is not related to pixel density, in the actual use of 1DP is approximately equal to 1/160inch.

So what does DP actually do to solve the problem with the adaptation? It can be seen that 1DP = 1/160inch; then it can at least solve one problem, that is, you write a view in the layout file width and height of 160dp*160dp, this view in any resolution of the screen, the size of the display is about the same (may be inaccurate), about 1 inch * 1 inch.

However, this does not solve all the adaptation problems:

    • The effect will still be different, just close.
    • When there is a difference in the physical size of the device, DP appears powerless. The UI for a 4.3-inch screen, running on a 5.0-inch screen, is likely to have plenty of white space on the right and the lower side. The 5.0-inch UI runs to a 4.3-inch device, which is probably not displayed.

Above two points from the reference link 1

In a nutshell, DP is able to allow the same value to show roughly the same size at different resolutions. But when the size of the device is different, there is nothing to do. The problem of adaptation also requires us to do it ourselves, and we may do so:

<?xml version= "1.0" encoding= "Utf-8"?>  <resources>      <!--values-hdpi 480X800 --      <dimen name="ImageWidth">120dip</dimen>      </Resources>  <resources>      <!--values-hdpi-1280x800 --      <dimen name="ImageWidth">220dip</dimen>      </Resources>  <?xml version= "1.0" encoding= "Utf-8"?>  <resources>      <!--values-hdpi 480X320 --      <dimen name="ImageWidth">80dip</dimen>      </Resources> 

The code snippet above comes from the network, that is, we still need to write multiple sets of numeric files for different DPI settings for a quality user experience.

As you can see, DP is not able to solve the adaptation problem. See below for percentages.

    • Percentage
      This concept goes without saying that the width of the supported controls in the Web can be used to refer to the width of the parent control to set the percentage, the outermost control's width reference screen size setting percentage, then in fact, in the Android device, only need to support the control can refer to the percentage of the screen to calculate the width is enough.

For example, I now have several requirements:

    • For the banner of the picture display, in order to have the effect, I want to display on any phone height of the screen height of 1/4
    • My homepage is divided into two columns, I want each column screen height is 11/24, the middle interval is 1/12
    • The width of the slidingmenu is 80% of the screen width

Of course, this is just a big level, but in fact a small-scale layout may be more useful as a percentage.

So now do not support the percentage, to achieve the above requirements, it may take 1, code to dynamic calculation (many people pass directly, too troublesome); 2, using weight (weight must rely on linearlayout, and can not be applied to any scenario)

Another example: the height and width of one of my floating buttons is expected to be 1/12 of the screen height, and one of my button widths is expected to be 1/3 of the width of the screen.

All of the above requirements, using DP is not possible, we want the size of the control can be written in the following ways:

   <Button        android:text="@string/hello_world"        android:layout_width="20%w"        android:layout_height="10%h"/>

Use the width and height of the screen to define the width and height of the view.

OK, so we can see the difference between DP and percent, and the percentage is better to solve our adaptation problem.

    • Some suitable tips

Let's take a look at some suitable tips

    1. Multi-use Match_parent
    2. Multi-use weight
    3. Custom View Resolution

In fact, the above 3 point tip, in the final analysis of the use of percentages, match_parent equivalent to 100% reference to the parent control, weight is prorated; Custom view is simply because most of the size is calculated as a percentage;

With these tips, we can see that if you can introduce a percentage mechanism into Android that will solve most of the adaptation issues, let's look at how we can get Android to support the concept of percent.

3, the introduction of the percentage of 1, introduced

In fact, our solution is to have a folder for each of your resumes in the project for the resolution of the phone screen you need to adapt.

Such as:

Then we are based on a benchmark, which means:

For example, the resolution of 480*320 is the benchmark

    • Width is 320, the width of any resolution is divided into 320 parts, the value is x1-x320
    • Height of 480, the height of any resolution is divided into 480 parts, the value is y1-y480

For example, the width of 800*480 480:

You can see x1 = 480/datum = 480/320 = 1.5;

Other resolutions similar to ~ ~
You might ask, so many files, do we have to hand it up and then write it ourselves? Don't be afraid, the following will say.

So, you may have a question, what good is this writing?

Suppose I now need a button in the center of the screen, width and height of 1/2 of our screen width, how can I write a layout file?

<FrameLayout >    <Button        android:layout_gravity="center"        android:gravity="center"        android:text="@string/hello_world"        android:layout_width="@dimen/x160"        android:layout_height="@dimen/x160"/></FrameLayout>

We can see that our width and height are defined as x160, which is actually 50% of the width;
So:

You can see that regardless of the resolution of the model, our buttons and height is always half the width of the screen.

    • For design drawings

Assuming that the current UI design is designed according to 480*320, and that the width and height of the logo above are PX values, you can directly convert px to x[1-320],y[1-480], so that the written layout is basically full-resolution adaptation.

You may ask: what if the resolution of the designer is not fixed? The following will say ~

    • For some of the above-mentioned DP does not work

You can try it by yourself after introducing a percentage

Well, there is a major problem, we did not say, is the resolution so much, do we have to calculate their own, and then handwritten?

2. Automatic Generation Tool

Well, actually this kind of folder handwriting can also, according to the resolution you need to support, and then write a set, have been used in the future.

Of course, as programmers, how can we do such a low job, it is certain to program to achieve:

Then the implementation requires the following steps:

    1. Analyze the required resolution for support

For the mainstream resolution I have integrated into our program, of course for special, you can specify by parameters. For screen resolution information, you can search through the site: Http://screensiz.es/phone

    1. Program to write automatically generated files

The code is as follows

ImportJava.io.File;ImportJava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.PrintWriter;/** * Created by Zhy on 15/5/3. * * Public  class generatevaluefiles {    Private intBasew;Private intBaseh;PrivateString Dirstr ="./res";Private Final StaticString wtemplate =" <dimen name=\" x{0}\ ">{1}px</dimen>\n ";Private Final StaticString htemplate =" <dimen name=\" y{0}\ ">{1}px</dimen>\n ";/** * {0}-height * *    Private Final StaticString value_template ="Values-{0}x{1}";Private Static FinalString support_dimesion ="320,480;480,800;480,854;540,960;600,1024;720,1184;720,1196;720,1280;768,1024;800,1280;1080,1812;1080,1920 ; 1440,2560; ";PrivateString supportstr = support_dimesion; Public Generatevaluefiles(intBaseX,intBasey, String supportstr) { This. Basew = BaseX; This. Baseh = Basey; This. supportstr + = ValidateInput (SUPPORTSTR);        System.out.println (SUPPORTSTR); File dir =NewFile (DIRSTR);if(!dir.exists ())        {Dir.mkdir ();    } System.out.println (Dir.getabsolutefile ()); }/** * @param supportstr * W,H;...W,H; * @return * *    PrivateStringValidateInput(String supportstr) {StringBuffer SB =NewStringBuffer (); string[] Vals = Supportstr.split (";");intW =-1;intH =-1; String[] WH; for(String val:vals) {Try{if(val = =NULL|| Val.length () = =0)Continue; WH = Val.split (","); W = Integer.parseint (wh[0]); h = integer.parseint (wh[1]); }Catch(NumberFormatException e) {System.err.println ("Skip Invalidate params:w,h ="+ val);Continue; } sb.append (W +","+ H +";"); }returnSb.tostring (); } Public void Generate() {string[] Vals = Supportstr.split (";"); for(String val:vals) {string[] wh = val.split (","); Generatexmlfile (Integer.parseint (wh[0]), Integer.parseint (wh[1])); }    }Private void Generatexmlfile(intWinth) {StringBuffer sbforwidth =NewStringBuffer (); Sbforwidth.append ("<?xml version=\" 1.0\ "encoding=\" utf-8\ "? >\n "); Sbforwidth.append ("<resources>");floatCELLW = w*1.0F/basew; System.out.println (W +","+ Basew +","+ CELLW); for(inti =1; i < Basew; i++) {Sbforwidth.append (Wtemplate.replace (' {0} ', i +""). Replace (' {1} ', Change (CELLW * i) +"")); } sbforwidth.append (Wtemplate.replace (' {0} ', Basew +""). Replace (' {1} ', W +"")); Sbforwidth.append ("</resources>"); StringBuffer sbforheight =NewStringBuffer (); Sbforheight.append ("<?xml version=\" 1.0\ "encoding=\" utf-8\ "? >\n "); Sbforheight.append ("<resources>");floatCELLH = H/baseh; for(inti =1; i < Baseh; i++) {Sbforheight.append (Htemplate.replace (' {0} ', i +""). Replace (' {1} ', Change (CELLH * i) +"")); } sbforheight.append (Htemplate.replace (' {0} ', Baseh +""). Replace (' {1} ', H +"")); Sbforheight.append ("</resources>"); File Filedir =NewFile (dirstr + file.separator + value_template.replace (' {0} ', H +"")//. replace (' {1} ', W +""));        Filedir.mkdir (); File Layxfile =NewFile (Filedir.getabsolutepath (),"Lay_x.xml"); File Layyfile =NewFile (Filedir.getabsolutepath (),"Lay_y.xml");Try{PrintWriter PW =NewPrintWriter (NewFileOutputStream (Layxfile));            Pw.print (Sbforwidth.tostring ());            Pw.close (); PW =NewPrintWriter (NewFileOutputStream (Layyfile));            Pw.print (Sbforheight.tostring ());        Pw.close (); }Catch(FileNotFoundException e)        {E.printstacktrace (); }    } Public Static float  Change(floatA) {inttemp = (int) (A * -);returnTemp/ -F } Public Static void Main(string[] args) {intBasew = the;intBaseh = -; String addition ="";Try{if(Args.length >=3) {Basew = Integer.parseint (args[0]); Baseh = Integer.parseint (args[1]); addition = args[2]; }Else if(Args.length >=1) {addition = args[0]; }        }Catch(NumberFormatException e) {System.err. println ("Right input params:java-jar xxx.jar width height w,h;w,h; ...; w,h; ");            E.printstacktrace (); System.exit (-1); }NewGeneratevaluefiles (Basew, Baseh, addition). Generate (); }}

At the same time I provide a jar package, by default, double-click to generate, instructions for use:

See at the end of the text, the built-in common resolution, the default benchmark is 480*320, of course, for special needs, through the command line to specify:

Example: Benchmark 1280 * 800, additional support size: 1152 * 735;4500 * 3200;

According to

Java-jar Xx.jar Width Height width,height_width,height

The above format can be.

By writing a tool to generate all the values that need to be adapted to the resolution according to a reference size, we can refer to the resolution of the screen when writing the layout file, and the design diagram given in the UI allows you to quickly write the layout according to the PX units it identifies. It basically solves the problem of adaptation.

The idea of the program has been put into use by the company, the individual think it is very good, if you have better solutions to solve the problem of screen adaptation, welcome message discussion or directly posted a good link, we can share their experience, so as to strengthen our team ~ ~.

Note: The idea of this program comes from Android day of the "blue-Shenzhen" group, with its consent to write this article, the above procedure also to a large extent borrowed from its shared source. Thanks in this logo, I wish its success in entrepreneurship!

ok~

Group No.: 264950424, welcome into the group

Public Number: Hongyangandroid
(Welcome attention, the first time to push the blog post information)

Reference links

Android multi-screen adaptation learning notes

Open source, original, practical Android screen adaptation program sharing

Android screen Adaptation Scheme

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.