android 用java写一个自动适配各种屏幕大小的工具

原创 2017年09月15日 17:53:14

思路:假设我当前机器屏幕宽高为1920*1116,我页面某个组件的宽度为100px,那么在1280*800的机器上,按道理将应该是100/1920*1280=66.66px,那么讲道理思路就来了,如果我在1920*1116适配了,那么宽按照1280/1920,高按照800/1116换算不就可以了吗?

难点:写配置文件

1.在应用资源文件下形成文件,比如我当前机器为1920*1116,我想1280*800也能用,就是两个文件夹:values-1920x1116,values-1280x800


  private final static String VALUE_TEMPLATE = "values-{0}x{1}";

  System.out.print("TEST::"+w+"?"+h);
        File fileDir = new File(dirStr + File.separator
                + VALUE_TEMPLATE.replace("{0}", w + "")//
                .replace("{1}", h + ""));
        fileDir.mkdir();

2,如果当前我的机器为1920*1116,那么我的values-1920x1116里就应该有横向的适配文件和纵向的适配文件,

    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";
 private void generateXmlFile(int w, int h) {

        StringBuffer sbForWidth = new StringBuffer();
        sbForWidth.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForWidth.append("<resources>");
        float cellw = w * 1.0f / baseW;

        System.out.println("width : " + w + "," + baseW + "," + cellw);
        for (int i = 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 = new StringBuffer();
        sbForHeight.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForHeight.append("<resources>");
        float cellh = h * 1.0f / baseH;
        System.out.println("height : " + h + "," + baseH + "," + cellh);
        for (int i = 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>");



        System.out.print("TEST::"+w+"?"+h);
        File fileDir = new File(dirStr + File.separator
                + VALUE_TEMPLATE.replace("{0}", w + "")//
                .replace("{1}", h + ""));
        fileDir.mkdir();

        File layxFile = new File(fileDir.getAbsolutePath(), "lay_x.xml");
        File layyFile = new File(fileDir.getAbsolutePath(), "lay_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();
        }
    }

附件:
package com.wyt.hcy.customviewtestdemo;

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

/**
 * created by hcy 
 */
public class WytCreateValueFiles {

    private int baseW;
    private int baseH;

    private String dirStr = "./app/src/main/res";

    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";

    /**
     * {0}-HEIGHT
     */
    private final static String VALUE_TEMPLATE = "values-{0}x{1}";

    private static final String SUPPORT_DIMESION = "1920,1116;";

    private String supportStr = SUPPORT_DIMESION;

    public WytCreateValueFiles(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(",");
            generateXmlFile(Integer.parseInt(wh[0]), Integer.parseInt(wh[1]));
        }

    }

    private void generateXmlFile(int w, int h) {

        StringBuffer sbForWidth = new StringBuffer();
        sbForWidth.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForWidth.append("<resources>");
        float cellw = w * 1.0f / baseW;

        System.out.println("width : " + w + "," + baseW + "," + cellw);
        for (int i = 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 = new StringBuffer();
        sbForHeight.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sbForHeight.append("<resources>");
        float cellh = h * 1.0f / baseH;
        System.out.println("height : " + h + "," + baseH + "," + cellh);
        for (int i = 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>");



        System.out.print("TEST::"+w+"?"+h);
        File fileDir = new File(dirStr + File.separator
                + VALUE_TEMPLATE.replace("{0}", w + "")//
                .replace("{1}", h + ""));
        fileDir.mkdir();

        File layxFile = new File(fileDir.getAbsolutePath(), "lay_x.xml");
        File layyFile = new File(fileDir.getAbsolutePath(), "lay_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;
    }

    /**
     *
     * @param args
     */

    public static void main(String[] args) {
        //当前屏幕宽高
        int baseW = 1280;
        int baseH = 800;
        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 WytCreateValueFiles(baseW, baseH, addition).generate();
    }

}

使用:如果当前机器为1280x800,那么就在

 public static void main(String[] args) {
        //当前屏幕宽高
        int baseW = 1280;
        int baseH = 800;
        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 WytCreateValueFiles(baseW, baseH, addition).generate();
    }

我想适配1920*1116

private static final String SUPPORT_DIMESION = "1920,1116;1024,600;";

运行就会在app/src/main/res 下生成文件

    private String dirStr = "./app/src/main/res";

然后替换布局文件将

        <com.wyt.hcy.customviewtestdemo.MyTextView
            android:layout_width="200px"
            android:layout_height="200px"
            android:layout_centerInParent="true"
            android:background="#0f0"/>

  <com.wyt.hcy.customviewtestdemo.MyTextView
            android:layout_width="@dimen/x200"
            android:layout_height="@dimen/y200"
            android:layout_centerInParent="true"
            android:background="#0f0"/>
横向x纵向y










版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Android 高德地图的定位功能,以及动态开启权限

配置工程 Eclipse 配置工程:http://lbs.amap.com/api/android-location-sdk/guide/create-project/eclipse-create-p...

Android必知必会-App 常用图标尺寸规范汇总

转自http://blog.csdn.net/ys743276112/article/details/51910874 1. 程序启动图标(icon launcher) 放...

为微信开发填坑:微信网页支付的开发流程及填坑技巧

GitChat 作者:极笔北客 小程序作为微信之父张小龙钦点,并多次公开为之宣传造势的产品,在微信之后是仅有的一次。正因为这种特殊的优待,在小程序上线后,据说内测资格一度从100w被炒到300w...

Android开发中 ic_launcher 尺寸

drawable-hdpi/ic_launcher.png (72x72 px)drawable-mdpi/ic_launcher.png (48x48 px)drawable-xhdpi/ic_la...

Android"挂逼"修炼之行---微信中定位照片的位置信息插件开发详解

最近关于微信中,朋友之间发送原图就可能暴露你的位置信息,其实这个问题不在于微信,微信是为了更好的体验效果,才有发送原图功能,而对于拍照,发送普通图片微信后台都会过滤图片的exif信息,这样就不会携带位...

图说Java —— 理解Java机制最受欢迎的8幅图

世间总是一图胜过千万言! 下面的8幅图来自于 Program Creek 的 Java教程 ,目前这是该网站最受欢迎的文章. 希望本文能帮你回顾你已经知道的那些知识。如果图片讲解的不够清晰...

Android 自定义字体样式 及系统默认字体样式 的设置

Android   能添加文字的控件都可以设置字体样式   关键字是:Typeface   在Java代码中设置或者在xml文件里面设置都可以 Android系统默认给出四种样式的字体 ,...

安卓实现扫一扫识别数字

公司业务需求,需要做手机号码的识别。所以有了此篇文章,现在就将实现过程分享给大家。

【玖哥乱弹】祭天时不同程序员的不同杀法

这两天一张“还杀了一个程序员祭天”的截图火了,很多同行在纷纷谴责这位无良老板的同时把矛头也指向了我,已经遇到好几个人问我:“作为程序员和一个杀程序员祭天的老板做校友是什么体验?”

iOS 【野路子】获取WKWebView内容高度做H5原生连接

前言:是这样的,刚写完上一篇文章还没缓过神来,上一篇文章我还提到了,想和大家聊聊原生+H5如何无缝连接的故事.结果我朋友就给我发了两篇他的作品.他的做法也都有独到之处.好的文章都是这样,让你每次看都能...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)