今日头条的相关方案
根据原理实现的第三方库
AndroidAutoSize
原理相关的博客
使用
如果只用今日头条的适配方案,只需要在蓝湖上选择android视图
然后根据设计图显示的数据,显示多少写多少就行了
实时预览
公司的项目目前设计图宽度是375dp*937dp
如果要实时预览该大小。需要如下操作。
创建虚拟设备
计算
主要是Screen Size 屏幕尺寸(屏幕对角线长度单位英寸)
以适配宽度为例
使用以下值效果正确。适配375dp宽度的设计图
5英寸,1125*2120
使用
效果
从其他适配方案迁移
之前项目使用的是形如px_xx的适配方案。其原理是把屏幕分成1080等分。需要将其迁移。
以下工具可以将res目录下所有的xml文件中的px_xx转换成对应的dp值
在标准设计图中屏幕宽度是375dp
而在px_xx中将屏幕分割成1080
所以对应的px_xx=(xx/2.88)dp
import javax.swing.plaf.TextUI;
import java.io.*;
import java.util.function.Function;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
//@dimen/px_
// String path="D:\\TRS_GIT\\NMIP\\WenZhouNews\\nmip_android\\app\\src\\main\\res\\layout\\layout_activity_edit_address.xml";
dealDirectory("D:\\TRS_GIT\\NMIP\\WenZhouNews\\nmip_android\\app\\src\\main\\res\\");
}
private static void dealDirectory(String path){
File file=new File(path+"\\");
File[] files = file.listFiles();
if(files==null){
return;
}
for(int i=0;i<files.length;i++){
if(files[i].isDirectory()){
dealDirectory(files[i].getPath());
}else{
changePx2dp(files[i].getPath());
}
}
}
private static void changePx2dp(String path){
if(path==null||"".equals(path)||!path.endsWith("xml")){
//只处理xml文件
return;
}
File file=new File(path);
StringBuilder stringBuffer=new StringBuilder();
try {
BufferedReader bufferedReader=new BufferedReader(new FileReader(file));
String line=null;
do{
line = bufferedReader.readLine();
if(line!=null) {
stringBuffer.append(line).append("\n");
}
}while (line!=null);
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
String pattern = "@dimen/px_(\\d+)";
Pattern r = Pattern.compile(pattern);
String str = stringBuffer.toString();
Matcher matcher = r.matcher(str);
String resultStr = matcher.replaceAll(new Function<MatchResult, String>() {
@Override
public String apply(MatchResult matchResult) {
int pxValue = Integer.parseInt(matchResult.group(1));
float dbValue = (float) (pxValue * 1.0f / 2.88 );
return String.format("%.2fdp",dbValue);
}
});
if(str.equals(resultStr)){
return;
}
// System.out.println(resultStr);
try {
OutputStreamWriter fileOutputStream=new OutputStreamWriter(new FileOutputStream(file));
fileOutputStream.write(resultStr);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
代码中也使用了
使用的地方还很多。为了降低迁移工作。这部分就生成一个dimens文件。将px_xx 映射为(xx/2.88)dp
生成dimens工具类
运行一下,在控制台中将打印相关数据,复制粘贴到对应文件即可。
public class BuildPx {
public static void main(String[] args) {
// <dimen name="px_43">5dp</dimen>
StringBuilder buffer=new StringBuilder();
for(int i=0;i<=1080;i++){
float dpValue= (float) (i*1.0f/2.88);
String format = String.format("<dimen name=\"px_%d\">%.2fdp</dimen>", i, dpValue);
buffer.append(format).append("\n");
}
System.out.println(buffer.toString());
}
}