Android 多屏幕適配方案

最近稍微有點時間,整理下先前寫的一個工具,發現還是很有用的,就想分享一下,希望能給大家帶來幫助,

廢話不多數,直接上代碼,之後再說原理。

public class MakeXml {
    private final static String rootPath = "D:\\work-space\\android\\dome\\MyApplication\\app\\src\\main\\res\\values-sw{0}dp\\";

    private final static float dw = 320f;
    private final static String DtemplateDp = "<dimen name=\"dimen_dp_{0}\">{1}dp</dimen>\n";
    private final static String DtemplateSp = "<dimen name=\"dimen_sp_{0}\">{1}sp</dimen>\n";
    public static void main(String[] args) {
        makeString(320);
        makeString(340);
        makeString(360);
        makeString(400);
        makeString(480);
        makeString(520);
        makeString(600);
        makeString(720);
        makeString(820);
    }

    public static void makeString(int w) {

        StringBuffer sb = new StringBuffer();
        sb.append("<resources>");
        float cellw = w / dw;
        for (int i = 1; i <= 450; i++) {
            sb.append(DtemplateDp.replace("{0}", i + "").replace("{1}",
                    change(cellw * i) + ""));
            if (i<50) {
                sb.append(DtemplateSp.replace("{0}", i + "").replace("{1}",
                        change(cellw * i) + ""));
            }
        }
        sb.append("</resources>");
        String path = rootPath.replace("{0}", w + "");
        File rootFile = new File(path);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        File layxFile = new File(path + "dimens_"+ w +".xml");
        try {
            PrintWriter pw = new PrintWriter(new FileOutputStream(layxFile));
            pw.print(sb.toString());
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

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

 

 

這是一個完整的類工具,單獨執行他   rootPath  用於配置生成的路徑。生成的是不同分辨率下的dp 和sp 單位名

values-swXXdp  ,看到這裏可能有人感到不陌生了,sw 標準,不懂得朋友可以腦補下,最小寬度適配原則。

 

使用: 如 

android:layout_height="@dimen/dp_25"
這個在不同分辨率屏幕上的大小是不一樣的,從而可以一套代碼適配手機和屏幕,時間問題,我就不多說了。
同時還有文字大小 
android:textSize="@dimen/sp_10"

和dp 單位同理,不同分辨率調用同樣是

sp_10  大小是不一樣的,這是我對適配的方案。如果你有更好的方案可以留言交流下。

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章