android屏幕適配,生成不一樣分辨率的dimen.xml文件

一.在項目下新建moudle,選擇Java Library

 

二.DimenUtils類

public class DimenUtils {
    //文件保存的路徑  是在該項目下根路徑下建立  好比該項目建立的路徑是E:\project3.0\,
    // 則保存的文件路徑是E:\project3.0\DimenDemo\app\src\main\res\values-1920x1080\dimen.xml
    private final static String rootPath = "app/src/main/res/values-{0}x{1}";


    private final static float dw = 1080f;//默認佈局的寬
    private final static float dh = 720f;//默認佈局的高

    private final static String WTemplate = "<dimen name=\"x{0}\">{1}px</dimen>\n";
    private final static String HTemplate = "<dimen name=\"y{0}\">{1}px</dimen>\n";
    public static void main(String[] args) {
        makeString(1080, 720);
        makeString(1920, 1080);
        makeString(1366, 768);
    }

    //獲取dimen.xml的文本內容
    public static void makeString(int w,int h){
        System.out.println("1111111111");
        StringBuffer sb=new StringBuffer();
        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sb.append("<resources>");

        //遍歷獲取一系列寬的值
        float cellw =w / dw;//寬的比例
        for (int i = 0; i <dw ; i++) {
            sb.append(WTemplate.replace("{0}",i + "").replace("{1}",
                    change(cellw * i) + ""));
        }

        sb.append(WTemplate.replace("{0}",dw+"").replace("{1}", w + ""));

        //遍歷獲取一系列高的值
        float cellh=h/dh;//高的比例
        for (int i = 0; i <dh ; i++) {
            sb.append(HTemplate.replace("{0}",i + "").replace("{1}",
                    change(cellh * i) + ""));
        }

        sb.append(HTemplate.replace("{0}",dh+"").replace("{1}", h+ ""));
        sb.append("</resources>");

        makeFile(w,h,sb.toString());
    }

    //建立文件並寫入內容
    private static void makeFile(int w,int h,String text){
        System.out.println("22222222222222");
        String path = rootPath.replace("{0}",w+ "").replace("{1}",h+ "");
        File rootFile = new File(path);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        File file=new File(path,"dimen.xml");
        System.out.println("333333333333333:"+file.getAbsolutePath());
        try {
            PrintWriter pw=new PrintWriter(new FileOutputStream(file));
            pw.println(text);
            pw.close();
            System.out.println("4444444444444444");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("5555555555555555");
        }
    }



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

三.運行生成文件

相關文章
相關標籤/搜索