专栏首页刘晓杰android多屏适配

android多屏适配

现在通用的多屏适配有如下三种

1.match_parent
2.weight
3.多个文件夹(small,normal,large,and extra large),然后分别给出(计算)控件大小

第一个和第二个比较好理解,但是应用范围比较窄.比如我需要一个长宽均为屏幕一半的button并且要在屏幕正中间.用match_parent肯定不行,用weight可以倒是可以,但是不觉得还要多用好几个控件把空白地方撑满不方便吗?这只是个demo,如果在项目中呢?那么就只能采用第三种

参考文章: http://blog.csdn.net/lmj623565791/article/details/45460089 http://www.cnblogs.com/soaringEveryday/p/4835839.html

接下来我就讲讲具体怎么做

1.计算屏幕的宽和高

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels; // 得到宽度
        int height = dm.heightPixels; // 得到高度
        Log.e("DisplayMetrics", height + "*" + width);

2.用GenerateValueFiles.java(Java工程)生成对应的values文件夹

这个文件我是从参考文章中拿下来并且修改过的.为了区分横屏还是竖屏,我把竖屏的文件夹名字添加了land标记 输入一次w和h 输出两个文件夹values-h*w(竖屏专用)和values-land-w*h(横屏),每次只要选一个就行

3.把values文件夹copy进android工程

接下来我用虚拟机演示一下

(1)横屏

数据显示w=2560,h=1504 GenerateValueFiles文件的main函数指明了参数的规则

所以

private static final String SUPPORT_DIMESION = "2560,1504;";

生成的文件夹如下

由于这是横屏,所以只需要values-land-2560x1504这个文件夹

(2)竖屏

ctrl+F11切换竖屏

GenerateValueFiles文件里面

private static final String SUPPORT_DIMESION = "2560,1504;1600,2464;";

生成的文件夹

这次我只需要黑色的文件夹

(3)展示

android工程的文件夹res目录如下,就是多了两个对应的文件夹

布局文件如下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context="com.example.multiscreen.MainActivity" >

    <Button
        android:layout_width="@dimen/x160"
        android:layout_height="@dimen/y240"
        android:gravity="center"
        android:text="Button" />

</RelativeLayout>

参考文章里说的很清楚,把宽度分成320分,那么160份就是整个屏幕的一半

运行看效果

忘了把GenerateValueFiles.java代码贴出来

public class GenerateValueFiles {

    private int baseW;
    private int baseH;

    private String dirStr = "./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 POTARIT_VALUE_TEMPLATE = "values-{0}x{1}";

    /**
     * {0}-WIDTH
     */
    private final static String LAND_VALUE_TEMPLATE = "values-land-{0}x{1}";

    private static final String SUPPORT_DIMESION = "2560,1504;1600,2464;";

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

    }

    /**
     * 竖屏
     */
    private void generatePotraitXmlFile(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>");

        File fileDir = new File(dirStr + File.separator
                + POTARIT_VALUE_TEMPLATE.replace("{0}", h + "")//
                        .replace("{1}", w + ""));
        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();
        }
    }

    /**
     * 横屏
     */
    private void generateLandXmlFile(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>");

        File fileDir = new File(dirStr + File.separator
                + LAND_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;
    }

    public static void main(String[] args) {
        int baseW = 320;
        int baseH = 480;
        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();
    }

}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • TCP长链接介绍

    TCP连接以后不主动断开连接.区别于短链接(三次握手四次分手算一次短链接),优点是避免短时间内重复连接所造成的信道资源以及网络资源的浪费

    提莫队长
  • Android:网络编程及Internet应用

    HttpURLConnection urlConn =(HttpURLConnection)url.openConnection();

    提莫队长
  • listview过滤item(基于ArrayAdapter和BaseAdapter)

    ArrayAdapter有个专门的函数用于过滤getFilter,所以只需要运用这个函数就行

    提莫队长
  • 聊聊spring cloud的DiscoveryClientRouteDefinitionLocator

    本文主要研究一下spring cloud的DiscoveryClient Route Definition Locator

    codecraft
  • 简单的java实验,涉及到 类继承以及接口问题,方法体的重写(区别于重载)

    1 package test ; 2 abstract class Animal 3 { 4 abstract void cry(); ...

    Gxjun
  • 史上最详细的Yolov3边框预测分析

    我们读yolov3论文时都知道边框预测的公式,然而难以准确理解为何作者要这么做,这里我就献丑来总结解释一下个人的见解,总结串联一下学习时容易遇到的疑惑,期待对大...

    BBuf
  • c++ 指针(一)

     指针:是说指针名表示的是地址。是一个变量,存储的是值的地址,而不是值本身  *运算符被称为间接值或解除引用运算符也可以叫做取地址符  声明一个指针  int ...

    lpxxn
  • Python每日一题:__new__ 与 __init__

    首先,我们来看下第一个作用,比如我们有一种需求,是一直要得到大写的字符串,类似新增一种数据类型,它会一直返回字符串的大写形式。我们就可以用 __new__ 来实...

    用户7685359
  • 一文搞懂 Flink如何移动计算

    对于分布式框架来说,我们经常听到的一句话就是:移动计算,不移动数据。那么对于 Flink 来说是如何移动计算的呢?我们一起重点看一下 ExecuteGraph

    shengjk1
  • 大数据应用之Windows平台Hbase客户端Eclipse开发环境搭建

      大数据的场景下,NoSql型数据库的优势不言而喻,但是涉及NoSQL数据库的实际动手开发的东西多是Linux平台,大多语焉不详,至于Windows平台介绍的...

    数据饕餮

扫码关注云+社区

领取腾讯云代金券