专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > XML/SOAP

android 屏幕适配一 ——dimens.xml的适配

发布时间:2010-05-20 14:01:29 文章来源:www.iduyao.cn 采编人员:星星草
android 屏幕适配1 ——dimens.xml的适配

1.如果是才开始做项目,已经有设计图:720*1280

1).默认values文件夹: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).720*1280像素对应的values-w720dp文件: 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).1080*1920像素对应的values-w1080dp文件: 【以720*1280位基准数作倍数换算

values-w1080dp/dimens_x.xml:

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

<dimen name="x1">3.0px</dimen> 倍数换算:倍数=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> 倍数换算:倍数=Height/baseH=1920/1280=1.5  value=1.5*2px=3.0px

 备注:

1.倍数即屏幕像素密度:例子中用的是常用的手机像素密度,但市面上手机像素密度参差不齐,跟你测试的实际手机像素密度可能不一样,但一般用常用的像素密度来换算

2.若以dp为单位

1).values下的文件,如下:

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).values-w720dp下,如下:

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.项目完成之后,则将values下面的dimens.xml 文件

按照不同分辩率的手机生成对应倍数的不同像素的dimens.xml文件

 eg:以720*1280为例子

values/dimens.xml :1dp=1px

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

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

<dimen name="x1">0.5dp</dimen> 倍数换算:  1dp=2px  720px=360dp    倍数=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("rn");  
  
                    sw480.append(start).append(num * 1.5).append(end).append("rn");  
  
                    sw600.append(start).append(num * 1.87).append(end).append("rn");  
  
                    sw720.append(start).append(num * 2.25).append(end).append("rn");  
  
                    sw800.append(start).append(num * 2.5).append(end).append("rn");  
  
                    w820.append(start).append(num * 2.56).append(end).append("rn");  
  
  
  
                } 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();  
  
    }  
  
}

 

友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: