前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android多屏适配

android多屏适配

作者头像
提莫队长
发布2019-02-21 11:37:21
8580
发布2019-02-21 11:37:21
举报
文章被收录于专栏:刘晓杰刘晓杰

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

代码语言:javascript
复制
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.计算屏幕的宽和高

代码语言:javascript
复制
        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函数指明了参数的规则

这里写图片描述
这里写图片描述

所以

代码语言:javascript
复制
private static final String SUPPORT_DIMESION = "2560,1504;";

生成的文件夹如下

这里写图片描述
这里写图片描述

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

(2)竖屏

ctrl+F11切换竖屏

这里写图片描述
这里写图片描述

GenerateValueFiles文件里面

代码语言:javascript
复制
private static final String SUPPORT_DIMESION = "2560,1504;1600,2464;";

生成的文件夹

这里写图片描述
这里写图片描述

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

(3)展示

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

这里写图片描述
这里写图片描述

布局文件如下

代码语言:javascript
复制
<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代码贴出来

代码语言:javascript
复制
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();
    }

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年11月09日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.计算屏幕的宽和高
  • 2.用GenerateValueFiles.java(Java工程)生成对应的values文件夹
  • 3.把values文件夹copy进android工程
  • (1)横屏
  • (2)竖屏
  • (3)展示
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档