from pathlib import Path import xml.etree.ElementTree as ET from xml.sax.saxutils import quoteattr, escape ROOT = Path(__file__).resolve().parents[1] RES = ROOT / 'app/src/main/res' A = 'http://schemas.android.com/apk/res/android' P = 'http://schemas.android.com/apk/res-auto' def node(tag, parent=None, **attrs): element = ET.Element(tag) for key, value in attrs.items(): key = key.replace('__', ':') if key.startswith('app:'): key = '{' + P + '}' + key[4:] elif key != 'style': key = '{' + A + '}' + key element.set(key, str(value)) if parent is not None: parent.append(element) return element def dimensions(width='match_parent', height='wrap_content', **attrs): return dict(layout_width=width, layout_height=height, **attrs) def linear(parent=None, **attrs): return node('LinearLayout', parent, **dimensions(**attrs)) def text(parent, resource, style='DevicePreviewLabel', **attrs): return node('TextView', parent, style='@style/' + style, **dimensions(**attrs), text='@string/' + resource) def image(parent, resource, width, height, **attrs): return node('ImageView', parent, **dimensions(width, height, **attrs), contentDescription='@null', src='@mipmap/' + resource) def metric(parent, label, value, id, large=False, **attrs): block = linear(parent, orientation='vertical', **attrs) text(block, label, minHeight='17dp' if large else '15dp', textSize='14sp' if large else '12sp') text(block, value, 'DevicePreviewRealtime' if large else 'DevicePreviewValue', id='@+id/' + id, layout_marginTop='6dp', minHeight='29dp' if large else '19dp') return block def card(id, parent=None, **attrs): return node('androidx.cardview.widget.CardView', parent, id='@+id/' + id, **dimensions(**attrs), app__cardBackgroundColor='@android:color/white', app__cardCornerRadius='16dp', app__cardElevation='0dp', app__cardPreventCornerOverlap='false') def write_xml(path, root, comment): def render(element, depth=0): indent = ' ' * depth attrs = [] if depth == 0: attrs += [('xmlns:android', A), ('xmlns:app', P)] for key, value in element.attrib.items(): key = key.replace('{' + A + '}', 'android:').replace('{' + P + '}', 'app:') attrs.append((key, value)) lines = [indent + '<' + element.tag] lines += [indent + ' ' + key + '=' + quoteattr(value) for key, value in attrs] if len(element): lines[-1] += '>' for child in element: lines += ['', render(child, depth + 1)] lines += [indent + ''] else: lines[-1] += ' />' return '\n'.join(lines) (RES / path).write_text('\n' + '\n' + render(root) + '\n', encoding='utf-8') # 设备卡:上下文保留原卡片 ID,开关使用项目已有组件,不接入真实硬件指令。 device = card('cv_preview_device') content = linear(device, orientation='vertical', padding='14dp', minHeight='323dp') header = linear(content, id='@+id/ll_preview_device_header', orientation='horizontal', gravity='top') image(header, 'icon_home_device', '50dp', '50dp', id='@+id/iv_preview_device_icon') name = linear(header, width='0dp', layout_weight='1', layout_marginStart='10dp', orientation='vertical') text(name, 'device_preview_name', 'DevicePreviewDeviceName', id='@+id/tv_preview_device_name') online = linear(name, id='@+id/ll_preview_online', layout_marginTop='6dp', orientation='horizontal', gravity='center_vertical') node('View', online, **dimensions('8dp', '8dp'), id='@+id/view_preview_online_dot', background='@drawable/home_index_status_dot') text(online, 'device_home_online', 'DevicePreviewText', id='@+id/tv_preview_online', width='wrap_content', layout_marginStart='4dp', textSize='14sp', textColor='#22A45D', minHeight='17dp') realtime = linear(content, id='@+id/ll_preview_realtime', layout_marginTop='16dp', orientation='horizontal', gravity='center_vertical', baselineAligned='false') values = linear(realtime, width='0dp', layout_weight='1', orientation='vertical') metric(values, 'device_preview_power_label', 'device_preview_demo_power', 'tv_preview_power', large=True) metric(values, 'device_preview_temperature_label', 'device_preview_demo_temperature', 'tv_preview_temperature', large=True, layout_marginTop='16dp') image(realtime, 'icon_device_preview_product', '0dp', '116dp', layout_weight='1', id='@+id/iv_preview_product', scaleType='fitCenter') totals = linear(content, orientation='horizontal', baselineAligned='false', layout_marginTop='16dp') metric(totals, 'device_preview_total_electricity_label', 'device_preview_demo_total_electricity', 'tv_preview_total_electricity', width='0dp', layout_weight='1', layout_marginEnd='8dp') metric(totals, 'device_preview_total_time_label', 'device_preview_demo_total_time', 'tv_preview_total_time', width='0dp', layout_weight='1') power = linear(content, orientation='horizontal', gravity='center_vertical', minHeight='37dp', layout_marginTop='16dp', paddingHorizontal='10dp', background='@drawable/device_preview_panel_bg') text(power, 'device_preview_power_switch', 'DevicePreviewDeviceName', width='0dp', layout_weight='1') node('com.kyleduo.switchbutton.SwitchButton', power, id='@+id/switch_preview_power', **dimensions('45dp', '37dp'), paddingVertical='8dp', checked='true', contentDescription='@string/device_preview_power_switch', app__kswThumbDrawable='@drawable/device_timer_switch_thumb', app__kswThumbWidth='17dp', app__kswThumbHeight='17dp', app__kswThumbMargin='2dp', app__kswThumbRangeRatio='2.4', app__kswThumbRadius='8.5dp', app__kswBackRadius='10.5dp', app__kswBackColor='@color/device_preview_switch_track') write_xml('layout/device_preview_device_content.xml', device, '设备信息与累计指标;内容随字体自然增高,左右两列按可用宽度等分。') # 减排卡:四项指标和积分环等分宽度,使用相对布局而非固定屏幕坐标。 carbon = card('cv_preview_carbon') body = linear(carbon, orientation='vertical', padding='14dp', minHeight='324dp') title = linear(body, id='@+id/ll_preview_carbon_details', orientation='horizontal', gravity='center_vertical') text(title, 'device_preview_carbon_title', 'DevicePreviewHeading', width='0dp', layout_weight='1', layout_marginEnd='8dp', minHeight='19dp') image(title, 'icon_device_preview_arrow', '7dp', '12dp') data = linear(body, orientation='horizontal', baselineAligned='false', layout_marginTop='16dp', gravity='center_vertical') metrics = linear(data, width='0dp', layout_weight='1', layout_marginEnd='8dp', orientation='vertical') block = metric(metrics, 'device_preview_electricity_label', 'device_preview_demo_electricity', 'tv_preview_electricity') block[-1].set('{' + A + '}textColor', '#FF6900') metric(metrics, 'device_preview_usage_time_label', 'device_preview_demo_usage_time', 'tv_preview_usage_time', layout_marginTop='16dp') metric(metrics, 'device_preview_total_electricity_label', 'device_preview_demo_total_electricity', 'tv_preview_carbon_total_electricity', layout_marginTop='16dp') metric(metrics, 'device_preview_total_time_label', 'device_preview_demo_total_time', 'tv_preview_carbon_total_time', layout_marginTop='16dp') ring_area = node('androidx.constraintlayout.widget.ConstraintLayout', data, **dimensions('0dp', 'wrap_content'), layout_weight='1') ring = node('FrameLayout', ring_area, **dimensions('0dp', '0dp'), id='@+id/preview_points_progress', background='@drawable/device_preview_points_ring', importantForAccessibility='no', app__layout_constraintWidth_max='120dp', app__layout_constraintDimensionRatio='1:1', app__layout_constraintStart_toStartOf='parent', app__layout_constraintEnd_toEndOf='parent', app__layout_constraintTop_toTopOf='parent', app__layout_constraintBottom_toBottomOf='parent') center = linear(ring, height='wrap_content', layout_gravity='center', gravity='center', orientation='vertical') text(center, 'device_preview_demo_points', 'DevicePreviewValue', id='@+id/tv_preview_points', gravity='center') text(center, 'device_preview_points_label', layout_marginTop='3dp', gravity='center') text(body, 'device_preview_equivalent', id='@+id/tv_preview_equivalent', layout_marginTop='16dp', minHeight='37dp', paddingHorizontal='10dp', paddingVertical='10dp', background='@drawable/device_preview_panel_bg') write_xml('layout/device_preview_carbon_content.xml', carbon, '今日减排与累计使用数据;绿色积分环按容器宽度缩放,底部展示累计减排说明。') # 底部两张卡保持等高;操作文字允许两行,适配英文与折叠窗口。 actions = linear(orientation='horizontal', baselineAligned='false') savings = card('cv_preview_savings', actions, width='0dp', height='match_parent', layout_weight='1', layout_marginEnd='11dp') saving_body = linear(savings, orientation='vertical', padding='14dp', minHeight='224dp') text(saving_body, 'device_preview_savings_title', 'DevicePreviewSmallHeading', minHeight='19dp') metric(saving_body, 'device_preview_charcoal_label', 'device_preview_demo_charcoal', 'tv_preview_charcoal', layout_marginTop='16dp') metric(saving_body, 'device_preview_saving_label', 'device_preview_demo_saving', 'tv_preview_saving', layout_marginTop='16dp') image(saving_body, 'icon_device_preview_tree', '28dp', '45dp', id='@+id/iv_preview_savings', layout_marginTop='20dp') quick = card('cv_preview_actions', actions, width='0dp', layout_weight='1') quick_body = linear(quick, orientation='vertical', padding='14dp', minHeight='224dp') text(quick_body, 'device_preview_actions_title', 'DevicePreviewSmallHeading', minHeight='19dp') for i, (container, label_id, label, icon) in enumerate([ ('ll_preview_stats', 'tv_carbon_status', 'device_preview_stats', 'icon_device_preview_stats'), ('ll_preview_control', 'tv_preview_control', 'device_preview_control', 'icon_device_preview_control'), ('ll_preview_carbon_points', 'tv_carbon_points', 'device_preview_carbon_points', 'icon_device_preview_points'), ]): row = linear(quick_body, id='@+id/' + container, orientation='horizontal', gravity='center_vertical', minHeight='45dp', layout_marginTop='16dp' if i == 0 else '13dp', background='@drawable/device_preview_panel_bg', foreground='?attr/selectableItemBackground', clickable='true', focusable='true', paddingHorizontal='10dp', paddingVertical='5.5dp') image(row, icon, '25dp', '25dp') text(row, label, 'DevicePreviewAction', id='@+id/' + label_id, width='0dp', layout_weight='1', layout_marginStart='10dp', layout_marginEnd='4dp') image(row, 'icon_device_preview_arrow', '7dp', '12dp', alpha='0.5') write_xml('layout/device_preview_actions_content.xml', actions, '今日节省和快捷操作;整行响应点击,英文文案允许换行。') # 两种窗口布局同步外层间距和标题栏,颜色仅作用本页,避免影响其他设备页面。 for name in ['layout/device_preview.xml', 'layout-w720dp/device_preview.xml']: path = RES / name xml = path.read_text(encoding='utf-8') xml = xml.replace('@color/device_preview_background', '@color/device_preview_page_background') xml = xml.replace('android:paddingHorizontal="25dp"', 'android:paddingHorizontal="24dp"') xml = xml.replace('android:paddingTop="7dp"', 'android:paddingTop="20dp"') xml = xml.replace('android:layout_marginTop="12dp"', 'android:layout_marginTop="10dp"') # 标题采用本页布局,不全局修改通用标题样式。 start = xml.index(' ''' + xml[end:] path.write_text(xml, encoding='utf-8')