本文转载自
fljustdoit
查看原文
2016-09-10
0
開發android項目,需要進行多分辨率適配,能夠支持國內主流的分辨率手機,總結一下,分為三個階段:
一、一開始再做適配工作如果分辨率很接近就使用同一套xml布局文件,分辨率差距較大就會重新寫一套,這樣會很耗時間。
二、后來使用dimens文件,通過在xml中使用dimens文件確實可以幫助我們省去大多數時間。但是最近又遇到一個問題,就是有新的機型需要適配時,特別是提測的前期,需要根據dpi和密度計算出新分辨率下各種寬高值,如果你的項目很龐大,那么工作量也是不小的,最關鍵問題是手動計算很可能會出錯,后來就自己寫了一個小東西,根據標准分辨率自動生成新分辨率的dimens文件,省去很多事。
三、在這份代碼中,以960X540分辨率為參照,生成800X480和854X480兩種分辨率的dimens文件,具體代碼如下:
public class DimenTool {
//參照分辨率dimens文件路徑
public static final String dimensPath = "D:/workspace/res/values-hdpi/dimens.xml";
public static final String h800dimensPath = "D:/workspace/values-hdpi-800X480/dimens.xml";
public static final String h854dimensPath = "D:/workspace/values-hdpi-854X480/dimens.xml";
public static void main(String[] args) {
produceDimens();
}
public static void produceDimens() {
//以此文件夾下的dimens.xml文件內容為初始值參照
File file = new File(dimensPath);
BufferedReader reader = null;
// StringBuilder mdpi = new StringBuilder();
//hdpi-800x480
StringBuilder h800 = new StringBuilder();
//hdpi-854x480
StringBuilder h854 = new StringBuilder();
try {
reader = new BufferedReader(new FileReader(file));
String tempString;
int line = 1;
while ((tempString = reader.readLine()) != null) {
if (tempString.contains("")) {
String start = tempString.substring(0, tempString.indexOf(">") + 1);
String end = tempString.substring(tempString.lastIndexOf("
//截取標簽內的內容,從>右括號開始,到左括號減2,取得配置的數字
Double num = Double.parseDouble
(tempString.substring(tempString.indexOf(">") + 1,
tempString.indexOf("") - 2));
//此時區分vertical和horizontal,根據不同的尺寸計算新的值,拼接新的字符串,並且結尾處換行。
if(start.contains("vertical_dp")){
//mdpi.append(start).append(num / 1).append(end).append("\r\n");
h800.append(start).append((int)(num*5/6)).append(end).append("\r\n");
h854.append(start).append((int)(num*0.889)).append(end).append("\r\n");
}else if (start.contains("horizontal_dp")){
//mdpi.append(start).append(num / 1).append(end).append("\r\n");
h800.append(start).append((int)(num*8/9)).append(end).append("\r\n");
h854.append(start).append((int)(num*8/9)).append(end).append("\r\n");
}else{
h800.append(start).append(num).append(end).append("\r\n");
h854.append(start).append(num).append(end).append("\r\n");
}
} else {
// mdpi.append(tempString).append("");
h800.append(tempString).append("");
h854.append(tempString).append("");
}
line++;
}
reader.close();
System.out.println("");
System.out.println(h800);
System.out.println("");
System.out.println(h854);
String h800_file = h800dimensPath;
String h854_file = h854dimensPath;
writeFile(h800_file, h800.toString());
writeFile(h854_file, h854.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
/**
* 寫入方法
*/
public static void writeFile(String file, String text) {
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
out.println(text);
} catch (IOException e) {
e.printStackTrace();
}
out.close();
}
希望多大家有幫助!