全局修改dp/sp
可用于不同密度设备的适配,将xml文件放到指定目录,设置缩放因子
import os
import re
def adjust_values(content, factor):
# 调整dp值和sp值
content = re.sub(r'(\d+)(dp|sp)', lambda m: f"{int(float(m.group(1)) * factor)}{m.group(2)}", content)
return content
def process_file(file_path, factor):
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
adjusted_content = adjust_values(content, factor)
with open(file_path, 'w', encoding='utf-8') as file:
file.write(adjusted_content)
print(f"成功处理: {file_path}")
except Exception as e:
print(f"处理文件 {file_path} 时出错: {str(e)}")
def process_directory(directory_path, factor):
for root, dirs, files in os.walk(directory_path):
for file in files:
if file.endswith('.xml'):
file_path = os.path.join(root, file)
process_file(file_path, factor)
# 使用示例
directory_path = "xml" # XML文件所在目录的路径
adjustment_factor = 0.5 # 调整因子
process_directory(directory_path, adjustment_factor)
假如文件命名为adjust_xml_values.py,则在命令行运行
python adjust_xml_values.py