Android screen adaptation 1 - adaptation of dimens.xml

1. If you are just starting the project, you already have a design drawing: 720*1280

1). Default values ​​folder: 1dp=1px

values/dimens_x.xml:

 name: x1~x720   value:1px~720px           

<dimen name="x1">1.0px</dimen>

values/dimens_y.xml

 name: y1~y1280   value:1px~1280px

<dimen name="y1">1.0px</dimen>

2). The values-w720dp file corresponding to 720*1280 pixels:  1dp=2px

values-w720dp/dimens_x.xml:

 name: x1~x720   value:2px~1440px        

<dimen name="x1">2.0px</dimen>

values-w720dp/dimens_y.xml 

 name: y1~y1280   value:2px~2560px

<dimen name="y1">2.0px</dimen>

2). The values-w1080dp file corresponding to 1080*1920 pixels: [Convert with 720*1280-bit base number as a multiple ]

values-w1080dp/dimens_x.xml:

 name: x1~x720   value:3px~1080px     Width:1080  baseW:720 

<dimen name="x1">3.0px</dimen> Multiple conversion: multiple=Width/baseW=1080/720=1.5 value=1.5*2px=3.0px

values-w1080dp/dimens_y.xml:

 name: y1~y1280   value:3px~3840px        Height:1920   baseH:1280

<dimen name="y1">3px</dimen> Multiple conversion: multiple=Height/baseH=1920/1280=1.5 value=1.5*2px=3.0px

 Remark:

1. The multiple is the pixel density of the screen: In the example, the pixel density of the commonly used mobile phone is used, but the pixel density of the mobile phone on the market is uneven, and the pixel density of the actual mobile phone you are testing may be different, but the commonly used pixel density is generally used for conversion.

2. If the unit is dp

1). The files under values ​​are as follows:

values/dimens_x.xml 

name: x1~x720   value:1.0dp~720.0dp  

<dimen name="x1">1.0dp</dimen>

......

<dimen name="x720">720.0dp</dimen>

values/dimens_y.xml 

name:y1~y1280  value:1dp~1280.0dp

<dimen name="y1">1dp</dimen>

......

<dimen name="y1280">1280.0dp</dimen>

2). Under values-w720dp, as follows:

values-w720dp/dimens_x.xml 

name: x1~x720   value:0.5dp~360.0dp  

<dimen name="x1">0.5dp</dimen>

......

<dimen name="x720">360.0dp</dimen>

values-720dp/dimens_y.xml 

name:y1~y1280  value:0.5dp~640.0dp

<dimen name="y1">0.5dp</dimen>

......

<dimen name="y1280">640.0dp</dimen>

2. After the project is completed, put the dimens.xml file under the values

Generate dimens.xml files with different pixels of corresponding multiples according to mobile phones with different resolutions

 eg: Take 720*1280 as an example

values/dimens.xml :1dp=1px

<dimen name="x1">1dp</dimen>

values-w720dp/dimens.xml : 【720*1280】 

<dimen name="x1"> 0.5dp </dimen> multiple conversion: 1dp=2px 720px=360dp multiple=360/720=0.5

values-w1080dp/dimens.xml : 【1080*1920

<dimen name="x1">0.75dp</dimen> 倍数换算【以720作基准】:1080/720*0.5=0.75dp 

 

附:自动生成dimens.xml的代码:

1.项目才开始,生成竖屏的代码

package com.charlie.volley.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

/**
 * 屏幕适配,自动生成dimens.xml
 * @author Charlie
 *
 */
public class GenerateValueFiles {

    private int baseW;
    private int baseH;

    private String dirStr = "./res";

    private final static String WTemplate = "<dimen name=\"x{0}\">{1}dp</dimen>\n";
    private final static String HTemplate = "<dimen name=\"y{0}\">{1}dp</dimen>\n";
    /**
     * {0}-HEIGHT
     */
    private final static String VALUE_TEMPLATE = "values-{0}x{1}";
    private final static String VALUE_TEMPLATE1 = "values";

    private static final String SUPPORT_DIMESION = "720,1280;1536,2048;1080,1920";
    /**
     * 单位为px:倍数与屏幕分辨率有关,2.0f对应屏幕像素为:720*1280,生成的文件对应放在values-w720dp下面
     * 单位为dp:multiple=0.5f,对应屏幕像素为:720*1280,生成的文件对应放在values-w720dp下面
     */
    private final static float multiple=0.5f; 

    private String supportStr = SUPPORT_DIMESION;

    public GenerateValueFiles(int baseX, int baseY, String supportStr) {
        this.baseW = baseX;
        this.baseH = baseY;

        if (!this.supportStr.contains(baseX + "," + baseY)) {
            this.supportStr += baseX + "," + baseY + ";";
        }

        this.supportStr += validateInput(supportStr);

        System.out.println(supportStr);

        File dir = new File(dirStr);
        if (!dir.exists()) {
            dir.mkdir();

        }
        System.out.println(dir.getAbsoluteFile());

    }

    /**
     * @param supportStr
     *            w,h_...w,h;
     * @return
     */
    private String validateInput(String supportStr) {
        StringBuffer sb = new StringBuffer();
        String[] vals = supportStr.split("_");
        int w = -1;
        int h = -1;
        String[] wh;
        for (String val : vals) {
            try {
                if (val == null || val.trim().length() == 0)
                    continue;

                wh = val.split(",");
                w = Integer.parseInt(wh[0]);
                h = Integer.parseInt(wh[1]);
            } catch (Exception e) {
                System.out.println("skip invalidate params : w,h = " + val);
                continue;
            }
            sb.append(w + "," + h + ";");
        }

        return sb.toString();
    }

    public void generate() {
        String[] vals = supportStr.split(";");
        for (String val : vals) {
            String[] wh = val.split(",");
           if(Integer.parseInt(wh[0])==baseW){
               float multiple=1.0f;
               generateBaseXmlFile(Integer.parseInt(wh[0]), Integer.parseInt(wh[1]),multiple);
           }
            generateXmlFile(Integer.parseInt(wh[0]), Integer.parseInt(wh[1]));
        }
    }

private void generateBaseXmlFile(int w, int h,float multiple) {
        
        StringBuffer sbForWidth = new StringBuffer();
        sbForWidth.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForWidth.append("<resources>\n");
        float cellw = w * multiple / baseW;

        System.out.println("width : " + w + "," + baseW + "," + cellw);
        for (int i = 1; i <= baseW; i++) {
            sbForWidth.append("\t"+WTemplate.replace("{0}", i + "").replace("{1}",
                    change(cellw * i) + ""));
        }
//        sbForWidth.append("\t"+WTemplate.replace("{0}", baseW + "").replace("{1}",
//                w + ""));
        sbForWidth.append("</resources>");

        StringBuffer sbForHeight = new StringBuffer();
        sbForHeight.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForHeight.append("<resources>\n");
        float cellh = h *multiple/ baseH;
        System.out.println("height : "+ h + "," + baseH + "," + cellh);
        for (int i = 1; i <= baseH; i++) {
            sbForHeight.append("\t"+HTemplate.replace("{0}", i + "").replace("{1}",
                    change(cellh * i) + ""));
        }
//        sbForHeight.append("\t"+HTemplate.replace("{0}", baseH + "").replace("{1}",
//                h + ""));
        sbForHeight.append("</resources>");

        File fileDir = new File(dirStr + File.separator
                + VALUE_TEMPLATE1);
        fileDir.mkdir();
        File layxFile = new File(fileDir.getAbsolutePath(), "ch_dimens_x.xml");
        File layyFile = new File(fileDir.getAbsolutePath(), "ch_dimens_y.xml");
        System.out.println(fileDir.toString());
        try {
            PrintWriter pw = new PrintWriter(new FileOutputStream(layxFile));
            pw.print(sbForWidth.toString());
            pw.close();
            pw = new PrintWriter(new FileOutputStream(layyFile));
            pw.print(sbForHeight.toString());
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    private void generateXmlFile(int w, int h) {
        
        StringBuffer sbForWidth = new StringBuffer();
        sbForWidth.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForWidth.append("<resources>\n");
        float cellw = w * multiple / baseW;

        System.out.println("width : " + w + "," + baseW + "," + cellw);
        for (int i = 1; i <= baseW; i++) {
            sbForWidth.append("\t"+WTemplate.replace("{0}", i + "").replace("{1}",
                    change(cellw * i) + ""));
        }
//        sbForWidth.append("\t"+WTemplate.replace("{0}", baseW + "").replace("{1}",
//                w + ""));
        sbForWidth.append("</resources>");

        StringBuffer sbForHeight = new StringBuffer();
        sbForHeight.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForHeight.append("<resources>\n");
        float cellh = h *multiple/ baseH;
        System.out.println("height : "+ h + "," + baseH + "," + cellh);
        for (int i = 1; i <= baseH; i++) {
            sbForHeight.append("\t"+HTemplate.replace("{0}", i + "").replace("{1}",
                    change(cellh * i) + ""));
        }
//        sbForHeight.append("\t"+HTemplate.replace("{0}", baseH + "").replace("{1}",
//                h + ""));
        sbForHeight.append("</resources>");

        File fileDir = new File(dirStr + File.separator
                + VALUE_TEMPLATE.replace("{0}", h + "")//
                        .replace("{1}", w + ""));
        fileDir.mkdir();
        File layxFile = new File(fileDir.getAbsolutePath(), "ch_dimens_x.xml");
        File layyFile = new File(fileDir.getAbsolutePath(), "ch_dimens_y.xml");
        try {
            PrintWriter pw = new PrintWriter(new FileOutputStream(layxFile));
            pw.print(sbForWidth.toString());
            pw.close();
            pw = new PrintWriter(new FileOutputStream(layyFile));
            pw.print(sbForHeight.toString());
           
            
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static float change(float a) {
        int temp = (int) (a * 100);
        return temp / 100f;
    }

    public static void main(String[] args) {
        int baseW = 720;
        int baseH = 1280;
        String addition = "";
        try {
            if (args.length >= 3) {
                baseW = Integer.parseInt(args[0]);
                baseH = Integer.parseInt(args[1]);
                addition = args[2];
            } else if (args.length >= 2) {
                baseW = Integer.parseInt(args[0]);
                baseH = Integer.parseInt(args[1]);
            } 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);
        }

        new GenerateValueFiles(baseW, baseH, addition).generate();
    }

}

 2.项目才开始,生成横屏的代码

package com.charlie.volley.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

/**
 * 屏幕适配,自动生成dimens.xml
 * @author Charlie
 *
 */
public class GenerateValueFiles_land {

    private int baseW;
    private int baseH;

    private String dirStr = "./res";

    private final static String WTemplate = "<dimen name=\"x{0}\">{1}dp</dimen>\n";
    private final static String HTemplate = "<dimen name=\"y{0}\">{1}dp</dimen>\n";
    /**
     * {0}-HEIGHT
     */
    private final static String VALUE_TEMPLATE = "values-{0}x{1}";
    private final static String VALUE_TEMPLATE1 = "values";

    private static final String SUPPORT_DIMESION = "1280,720;2048,1536;";
    /**
     * 单位为px:倍数与屏幕分辨率有关,2.0f对应屏幕像素为:720*1280,生成的文件对应放在values-w720dp下面
     * 单位为dp:multiple=0.5f,对应屏幕像素为:720*1280,生成的文件对应放在values-w720dp下面
     */
    private final static float multiple=0.5f; 

    private String supportStr = SUPPORT_DIMESION;

    public GenerateValueFiles_land(int baseX, int baseY, String supportStr) {
        this.baseW = baseX;
        this.baseH = baseY;

        if (!this.supportStr.contains(baseX + "," + baseY)) {
            this.supportStr += baseX + "," + baseY + ";";
        }

        this.supportStr += validateInput(supportStr);

        System.out.println(supportStr);

        File dir = new File(dirStr);
        if (!dir.exists()) {
            dir.mkdir();

        }
        System.out.println(dir.getAbsoluteFile());

    }

    /**
     * @param supportStr
     *            w,h_...w,h;
     * @return
     */
    private String validateInput(String supportStr) {
        StringBuffer sb = new StringBuffer();
        String[] vals = supportStr.split("_");
        int w = -1;
        int h = -1;
        String[] wh;
        for (String val : vals) {
            try {
                if (val == null || val.trim().length() == 0)
                    continue;

                wh = val.split(",");
                w = Integer.parseInt(wh[0]);
                h = Integer.parseInt(wh[1]);
            } catch (Exception e) {
                System.out.println("skip invalidate params : w,h = " + val);
                continue;
            }
            sb.append(w + "," + h + ";");
        }

        return sb.toString();
    }

    public void generate() {
        String[] vals = supportStr.split(";");
        for (String val : vals) {
            String[] wh = val.split(",");
           if(Integer.parseInt(wh[0])==baseW){
               float multiple=1.0f;
               generateBaseXmlFile(Integer.parseInt(wh[0]), Integer.parseInt(wh[1]),multiple);
           }
            generateXmlFile(Integer.parseInt(wh[0]), Integer.parseInt(wh[1]));
        }
    }

private void generateBaseXmlFile(int w, int h,float multiple) {
        
        StringBuffer sbForWidth = new StringBuffer();
        sbForWidth.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForWidth.append("<resources>\n");
        float cellw = w * multiple / baseW;

        System.out.println("width : " + w + "," + baseW + "," + cellw);
        for (int i = 1; i <= baseW; i++) {
            sbForWidth.append("\t"+WTemplate.replace("{0}", i + "").replace("{1}",
                    change(cellw * i) + ""));
        }
//        sbForWidth.append("\t"+WTemplate.replace("{0}", baseW + "").replace("{1}",
//                w + ""));
        sbForWidth.append("</resources>");

        StringBuffer sbForHeight = new StringBuffer();
        sbForHeight.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForHeight.append("<resources>\n");
        float cellh = h *multiple/ baseH;
        System.out.println("height : "+ h + "," + baseH + "," + cellh);
        for (int i = 1; i <= baseH; i++) {
            sbForHeight.append("\t"+HTemplate.replace("{0}", i + "").replace("{1}",
                    change(cellh * i) + ""));
        }
//        sbForHeight.append("\t"+HTemplate.replace("{0}", baseH + "").replace("{1}",
//                h + ""));
        sbForHeight.append("</resources>");

        File fileDir = new File(dirStr + File.separator
                + VALUE_TEMPLATE1+"-land");
        fileDir.mkdir();
        File layxFile = new File(fileDir.getAbsolutePath(), "ch_dimens_x.xml");
        File layyFile = new File(fileDir.getAbsolutePath(), "ch_dimens_y.xml");
        System.out.println(fileDir.toString());
        try {
            PrintWriter pw = new PrintWriter(new FileOutputStream(layxFile));
            pw.print(sbForWidth.toString());
            pw.close();
            pw = new PrintWriter(new FileOutputStream(layyFile));
            pw.print(sbForHeight.toString());
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    private void generateXmlFile(int w, int h) {
        
        StringBuffer sbForWidth = new StringBuffer();
        sbForWidth.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForWidth.append("<resources>\n");
        float cellw = w * multiple / baseW;

        System.out.println("width : " + w + "," + baseW + "," + cellw);
        for (int i = 1; i <= baseW; i++) {
            sbForWidth.append("\t"+WTemplate.replace("{0}", i + "").replace("{1}",
                    change(cellw * i) + ""));
        }
//        sbForWidth.append("\t"+WTemplate.replace("{0}", baseW + "").replace("{1}",
//                w + ""));
        sbForWidth.append("</resources>");

        StringBuffer sbForHeight = new StringBuffer();
        sbForHeight.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForHeight.append("<resources>\n");
        float cellh = h *multiple/ baseH;
        System.out.println("height : "+ h + "," + baseH + "," + cellh);
        for (int i = 1; i <= baseH; i++) {
            sbForHeight.append("\t"+HTemplate.replace("{0}", i + "").replace("{1}",
                    change(cellh * i) + ""));
        }
//        sbForHeight.append("\t"+HTemplate.replace("{0}", baseH + "").replace("{1}",
//                h + ""));
        sbForHeight.append("</resources>");

        File fileDir = new File(dirStr + File.separator
                + VALUE_TEMPLATE.replace("{0}", w + "")//
                        .replace("{1}", h + "")+"-land");
        fileDir.mkdir();
        File layxFile = new File(fileDir.getAbsolutePath(), "ch_dimens_x.xml");
        File layyFile = new File(fileDir.getAbsolutePath(), "ch_dimens_y.xml");
        try {
            PrintWriter pw = new PrintWriter(new FileOutputStream(layxFile));
            pw.print(sbForWidth.toString());
            pw.close();
            pw = new PrintWriter(new FileOutputStream(layyFile));
            pw.print(sbForHeight.toString());
           
            
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static float change(float a) {
        int temp = (int) (a * 100);
        return temp / 100f;
    }

    public static void main(String[] args) {
        int baseW = 1280;
        int baseH = 720;
        String addition = "";
        try {
            if (args.length >= 3) {
                baseW = Integer.parseInt(args[0]);
                baseH = Integer.parseInt(args[1]);
                addition = args[2];
            } else if (args.length >= 2) {
                baseW = Integer.parseInt(args[0]);
                baseH = Integer.parseInt(args[1]);
            } 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);
        }

        new GenerateValueFiles_land(baseW, baseH, addition).generate();
    }

}

 3.项目已完成,作屏幕适配,根据已有的dimens.xml生成对应不同分辨率文件夹下的dimens.xml文件

package com.charlie.volley.utils;

import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.File;  
import java.io.FileOutputStream;
import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.io.PrintWriter;  
  
/** 
 * eclipse下使用
 * 
 * 屏幕适配,自动生成dimens.xml
 * @author Charlie
 *
 *
 * 快速生成适配工具类 
 * 工具类代码,直接运行即可,(如果提示 Invalid layout of preloaded class 错误 项目设置如下即可

Project->Properties->Run/Debug Settings;
Select your Class(DimenTool.java) and click "Edit";
Open the tab "Classpath" and remove Android Lib from "Bootstrap Entries";
Apply everything and Run the class again.
 */  
public class DimensUtils {  
  
    public static void gen() {  
        //以此文件夹下的dimens.xml文件内容为初始值参照  
        File file = new File("./res/values/dimens.xml");  
//        File file = new File("./app/src/main/res/values/dimens.xml");  android studio
  
        BufferedReader reader = null;  
        StringBuilder sw240 = new StringBuilder();  
        StringBuilder sw480 = new StringBuilder();  
        StringBuilder sw600 = new StringBuilder();  
  
        StringBuilder sw720 = new StringBuilder();  
  
        StringBuilder sw800 = new StringBuilder();  
  
        StringBuilder w820 = new StringBuilder();  
  
        try {  
  
            System.out.println("生成不同分辨率:");  
  
            reader = new BufferedReader(new FileReader(file));  
  
            String tempString;  
  
            int line = 1;  
  
            // 一次读入一行,直到读入null为文件结束  
  
            while ((tempString = reader.readLine()) != null) {  
  
  
                if (tempString.contains("</dimen>")) {  
  
                    //tempString = tempString.replaceAll(" ", "");  
  
                    String start = tempString.substring(0, tempString.indexOf(">") + 1);  
  
                    String end = tempString.substring(tempString.lastIndexOf("<") - 2);  
                    //截取<dimen></dimen>标签内的内容,从>右括号开始,到左括号减2,取得配置的数字  
                    Double num = Double.parseDouble  
                            (tempString.substring(tempString.indexOf(">") + 1,   
                                    tempString.indexOf("</dimen>") - 2));  
  
                    //根据不同的尺寸,计算新的值,拼接新的字符串,并且结尾处换行。  
                    sw240.append(start).append( num * 0.75).append(end).append("\r\n");  
  
                    sw480.append(start).append(num * 1.5).append(end).append("\r\n");  
  
                    sw600.append(start).append(num * 1.87).append(end).append("\r\n");  
  
                    sw720.append(start).append(num * 2.25).append(end).append("\r\n");  
  
                    sw800.append(start).append(num * 2.5).append(end).append("\r\n");  
  
                    w820.append(start).append(num * 2.56).append(end).append("\r\n");  
  
  
  
                } else {  
                    sw240.append(tempString).append("");  
  
                    sw480.append(tempString).append("");  
  
                    sw600.append(tempString).append("");  
  
                    sw720.append(tempString).append("");  
  
                    sw800.append(tempString).append("");  
  
                    w820.append(tempString).append("");  
  
                }  
  
                line++;  
  
            }  
  
            reader.close();  
            System.out.println("<!--  sw240 -->");  
  
            System.out.println(sw240);  
  
            System.out.println("<!--  sw480 -->");  
  
            System.out.println(sw480);  
  
            System.out.println("<!--  sw600 -->");  
  
            System.out.println(sw600);  
  
            System.out.println("<!--  sw720 -->");  
  
            System.out.println(sw720);  
  
            System.out.println("<!--  sw800 -->");  
  
            System.out.println(sw800);  
  
            String sw240file = "./res/values-sw240dp/dimens.xml";  
  
            String sw480file = "./res/values-sw480dp/dimens.xml";  
  
            String sw600file = "./res/values-sw600dp/dimens.xml";  
  
            String sw720file = "./res/values-sw720dp/dimens.xml";  
  
            String sw800file = "./res/values-sw800dp/dimens.xml";  
  
            String w820file = "./res/values-w820dp/dimens.xml";  
            //将新的内容,写入到指定的文件中去  
            writeFile(sw240file, sw240.toString());  
  
            writeFile(sw480file, sw480.toString());  
  
            writeFile(sw600file, sw600.toString());  
  
            writeFile(sw720file, sw720.toString());  
  
            writeFile(sw800file, sw800.toString());  
  
            writeFile(w820file, w820.toString());  
  
        } catch (IOException e) {  
  
            e.printStackTrace();  
  
        } finally {  
  
            if (reader != null) {  
  
                try {  
  
                    reader.close();  
  
                } catch (IOException e1) {  
  
                    e1.printStackTrace();  
  
                }  
  
            }  
  
        }  
  
    }  
  
  
    /** 
     * 写入方法 
     * 
     */  
  
    public static void writeFile(String file, String text) {  
  
        PrintWriter out = null;  
        
        try {  
  
//            out = new PrintWriter(new BufferedWriter(new FileWriter(file)));  
//  
//            out.println(text);  
             File fileDir = new File((String) file.subSequence(0, file.length()-11));
             fileDir.mkdir();
            out= new PrintWriter(new FileOutputStream(new File(file)));
            out.println(text);  
            out.close();
            
        } catch (IOException e) {  
  
            e.printStackTrace();  
  
        }  
  
  
  
        out.close();  
  
    }  
    public static void main(String[] args) {  
  
        gen();  
  
    }  
  
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326069804&siteId=291194637