1.在项目下新建moudle,选择Java Library,如图:
2.编写工具类:
public class DimenUtils {//文件保存的路径 是在该项目下根路径下创建 比如该项目创建的路径是C:\MyProject\,// 则保存的文件路径是C:\MyProject\DimensDemo\app\src\main\res\values-360x640\dimens.xml//sdk 3.2 之后可使用 values-sw600dp\命名文件夹private final static String rootPath = "app/src/main/res/values-{0}x{1}";private final static float dw = 360f;//默认布局的宽private final static float dh = 640f;//默认布局的高private final static String WTemplate = "<dimen name=\"dp_{0}\">{1}px</dimen>\n";
// private final static String HTemplate = "<dimen name=\"dp_{0}\">{1}px</dimen>\n";public static void main(String[] args) {
// makeString(1080, 720);
// makeString(1920, 1080);
// makeString(1366, 768);//平板makeString(1200, 1920);makeString(1536, 2048);makeString(1600, 2560);}//获取dimen.xml的文本内容public static void makeString(int w,int h){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){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");try {PrintWriter pw=new PrintWriter(new FileOutputStream(file));pw.println(text);pw.close();} catch (FileNotFoundException e) {e.printStackTrace();}}public static float change(float a) {int temp = (int) (a * 100);return temp / 100f;}
}
3.右键运行该文件,即可生成对应的dimens文件:


















