Skillfully use Dimens to fit multiple resolutions

Source: Internet
Author: User

Listen to the Moon. Published: 2013-02-27 11:16 Category: Android, project experience read: 3,034 plays 2 reviews

Having apps automatically adapt to screens with multiple resolutions is the basic skill of every Android programmer, as if the front-end engineer is skilled at writing CSS hack. An important task in the adaptation work is the adjustment of the page.

There are many methods and techniques for the adaptation of a page. For example, the layout of the use of Wrapcontent, Fillparent, as far as possible to avoid specific numbers, by the system to calculate the appropriate width, or write a set of layout files for each resolution, set the corresponding resolution of the width of the height of the control;

Write a set of layout files for each resolution although it is independent and simple enough. But the cost of maintenance is high. A page change, often involving multiple layout file changes, people are very painful.

Little Tricks

We can try to write only one set of XML layouts and then prepare multiple sets of dimension files for that layout.

In a more detailed way, the width of the component in the XML layout is not represented by a specific value, but instead is configured in the dimension file. The size of the values in each set of dimension files is calculated proportionally.

For example, at 1980*1080 resolution, the definition of px15 represents 15px

<dimen name= "px15" >15px</dimen>

Then at 1080 * 720 resolution, the px15 will be scaled down 1.5 times times, the definition px15 represents 10px

<dimen name= "px15" >10px</dimen>

So in the XML layout file, we can say this:


Android:layout_width= "@dimen/px150"

android:layout_height= "@dimen/px15"

android:orientation= "Vertical" >




This set of layout files in the LinearLayout at 1980 * 1080 resolution of the width of the height of x 15, at 1080 * 720 resolution of the wide high will automatically become 100 * 10

Other resolutions in the same vein


1. Some students ask questions, so it becomes necessary to maintain multiple sets of Dimenson files? A bottle?

In fact, for dimension files we can use code to control the generation, the range of values can be based on their own situation. Other resolutions only need to be proportional, use the code to calculate a bit.

Writing a generated code like this is not difficult, and we'll give it in the next article.

After the build is complete, the Values directory structure is as follows:

2. Proportional to the layout must be reliable, will not appear chaotic phenomenon

There may be, this time need to coordinate the layout of the use of the width of the high, choose the right width of the page at each resolution, it does not look outrageous on the line, not necessarily strictly according to the design. Most of the pages are compatible.

The above describes the use of dimension files to do the matching. said that using the code to automatically generate all the dimension files, next we give the relevant code.


Package com.example.test;


Import java.util.*;


* Dimens Data automatic generation tool


public class Dimenstools {

     /** Source file */

     static String Oldfilepath = "./res/values-nodpi/dimens.xml";

     /** new generated file path */

     static String filePath720 = "./res/values-1280x720/dimens.xml";

     /** new generated file path */

     static String filePath672 = "./res/values-1280x672/dimens.xml";

     /** new generated file path */

     static String filePath1080 = "./res/values-1920x1080/dimens.xml";

     /** Reduction Multiplier */

     static float changes = 1.5f;

     public static void Main (string[] args) {

          Generate 1-1920px

          String allpx= getallpx ();

          DeleteFolder (Oldfilepath);

          WriteFile (Oldfilepath, ALLPX);

          String st = convertstreamtostring (Oldfilepath, changes);

          DeleteFolder (filePath720);

          WriteFile (filePath720, ST);

          DeleteFolder (filePath672);

          WriteFile (filePath672, ST);

          String st1 = convertstreamtostring (Oldfilepath, 1f);

          DeleteFolder (filePath1080);

          WriteFile (filePath1080, ST1);


     /** read file Generate scaled String */

     public static string Convertstreamtostring (string filepath, float f) {

          StringBuilder sb = new StringBuilder ();

          try {

               BufferedReader bf = new BufferedReader (new FileReader (filepath));

               String line = null;

               System.out.println ("Q1");

               String Endmark = "px</dimen>";

               String Startmark = ">";

               while (line = Bf.readline ()) = null) {

                    if (Line.contains (Endmark)) {

                         int end = Line.lastindexof (Endmark);

                         int start = Line.indexof (Startmark);

                         String stpx = line.substring (start + 1, end);

                         int px = Integer.parseint (STPX);

                         int newpx = (int) ((float) px/f);

                         String newline = line.replace (px + "px", newpx + "px");

                         Sb.append (newline + "\ r \ n");

                    } else {

                         Sb.append (line + "\ r \ n");



               System.out.println (Sb.tostring ());

          } catch (IOException e) {

               E.printstacktrace ();


          return sb.tostring ();



     * Deletes the specified directory or file according to the path, regardless of whether it exists or not


     * @param spath

     *            the directory or file to be deleted

     * @return Delete succeeds returns True, otherwise false is returned.


     public static Boolean DeleteFolder (String spath) {

          File File = new file (spath);

          Determine if a directory or file exists

          if (!file.exists ()) {//does not exist return false

               return true;

          } else {

               Determine if the file is

               if (File.isfile ()) {//is a file when the delete file method is called

                    return DeleteFile (spath);

               The Delete directory method is called when the else {//is a directory

               return DeleteDirectory (spath);



          return false;


     /** Save As new file */

     public static void WriteFile (string filepath, string st) {

          try {

               FileWriter FW = new FileWriter (filepath);

               BufferedWriter bw = new BufferedWriter (FW);

               Bw.write (ST);

               Bw.flush ();

               Bw.close ();

          } catch (IOException e) {

               E.printstacktrace ();



     /** generate full px file */

     public static String getallpx () {

          StringBuilder sb = new StringBuilder ();

          try {

               Sb.append ("<resources>" + "\ r \ n");

               Sb.append ("<dimen name=\" screen_width\ ">1920px</dimen>" + "\ r \ n");

               Sb.append ("<dimen name=\" screen_height\ ">1080px</dimen>" + "\ r \ n");

               for (int i = 1; i <=; i++) {

                    System.out.println ("i=" +i);

                    Sb.append ("<dimen name=\" px "+ i +" \ ">" + i + "px</dimen>"

                              + "\ r \ n");


               Sb.append ("</resources>" + "\ r \ n");

               System.out.println (Sb.tostring ());

          } catch (Exception e) {

               E.printstacktrace ();


          return sb.tostring ();



     * Delete individual files


     * @param spath

     *            file name of deleted files

     * @return Single File Delete successfully returns TRUE, otherwise false


     public static Boolean DeleteFile (String spath) {

          Boolean flag = false;

          File File = new file (spath);

          The path is a file and is not empty to delete

          if (File.isfile () && file.exists ()) {

               File.delete ();

               Flag = true;


          return flag;



Usage: cmd under use Javac, Java command runs. It's a bit of a struggle, but let's use ant to write an automatic script.

Note: First set up the corresponding folder, 672 also according to 1.5 scale. Can be adjusted according to their own needs.

Skillfully use Dimens to fit multiple resolutions

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: 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.